aoc2015/d09/part1.py

39 lines
846 B
Python

import sys
import networkx as nx
G = nx.Graph()
D = {}
for l in sys.stdin.readlines():
l = l[:-1]
I = l.split(' ')
G.add_edge(I[0], I[2], weight=int(I[4]))
#G.add_edge(I[2], I[0], weight=int(I[4]))
D[(I[0], I[2])]=int(I[4])
D[(I[2], I[0])]=int(I[4])
def dfs_visit(graph, node, visited):
visited[node] = True
for neighbor in graph.neighbors(node):
if not visited[neighbor]:
dfs_visit(graph, neighbor, visited)
def dfs(graph):
visited = node: False for node in graph.nodes
for node in graph.nodes:
if not visited[node]:
dfs_visit(graph, node, visited)
# Call the DFS function and visit all nodes exactly once
dfs(G)
tsp = nx.approximation.traveling_salesman_problem
L = tsp(G)#, cycle=False)
print(L)
S = sum(D[(a,b)] for (a,b) in zip(L[1:],L[2:]))
print(S)