forked from mercari-build/week4-tsp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
solver_greedy.py
executable file
·39 lines (27 loc) · 940 Bytes
/
solver_greedy.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#!/usr/bin/env python3
import sys
import math
from common import print_solution, read_input
def distance(city1, city2):
return math.sqrt((city1[0] - city2[0]) ** 2 + (city1[1] - city2[1]) ** 2)
def solve(cities):
N = len(cities)
dist = [[0] * N for i in range(N)]
for i in range(N):
for j in range(N):
dist[i][j] = dist[j][i] = distance(cities[i], cities[j])
current_city = 0
unvisited_cities = set(range(1, N))
solution = [current_city]
def distance_from_current_city(to):
return dist[current_city][to]
while unvisited_cities:
next_city = min(unvisited_cities, key=distance_from_current_city)
unvisited_cities.remove(next_city)
solution.append(next_city)
current_city = next_city
return solution
if __name__ == '__main__':
assert len(sys.argv) > 1
solution = solve(read_input(sys.argv[1]))
print_solution(solution)