You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

44 lines
1.0 KiB
Python

import itertools
with open("input") as f:
connections = [n.strip() for n in f.readlines()]
GRAPH = dict()
LOCATIONS = set()
for connection in connections:
[location_a, _, location_b, _, distance] = connection.split(" ")
distance = int(distance)
LOCATIONS.add(location_a)
LOCATIONS.add(location_b)
GRAPH[(location_a, location_b)] = distance
GRAPH[(location_b, location_a)] = distance
def calculate_distance(route):
dist = 0
for i in range(len(route) - 1):
location_a = route[i]
location_b = route[i + 1]
if (location_a, location_b) not in GRAPH:
return None
dist += GRAPH[(location_a, location_b)]
return dist
SHORTEST_ROUTE = None
SHORTEST_DISTANCE = None
for route in itertools.permutations(LOCATIONS, len(LOCATIONS)):
dist = calculate_distance(route)
if dist is None:
continue
if SHORTEST_DISTANCE is None or dist < SHORTEST_DISTANCE:
SHORTEST_DISTANCE = dist
SHORTEST_ROUTE = route
print(SHORTEST_ROUTE)
print(SHORTEST_DISTANCE)