Optimized solution
This commit is contained in:
@@ -32,8 +32,6 @@
|
|||||||
from itertools import permutations
|
from itertools import permutations
|
||||||
|
|
||||||
import networkx as nx
|
import networkx as nx
|
||||||
import networkx.algorithms.approximation as nx_app
|
|
||||||
from networkx.classes.function import path_weight
|
|
||||||
|
|
||||||
with open("files/P9.txt") as f:
|
with open("files/P9.txt") as f:
|
||||||
routes = [line for line in f.read().strip().split("\n")]
|
routes = [line for line in f.read().strip().split("\n")]
|
||||||
@@ -44,13 +42,10 @@ for route in routes:
|
|||||||
from_, to_ = cities.split(" to ")
|
from_, to_ = cities.split(" to ")
|
||||||
G.add_edge(from_, to_, weight=int(dist))
|
G.add_edge(from_, to_, weight=int(dist))
|
||||||
|
|
||||||
cycle = nx_app.christofides(G, weight="weight")
|
|
||||||
|
|
||||||
paths = []
|
paths = []
|
||||||
for f, t in permutations(cycle, 2):
|
for route in permutations(G.nodes):
|
||||||
for path in nx.all_simple_paths(G, source=f, target=t):
|
distance = sum(G[u][v]["weight"] for u, v in zip(route, route[1:]))
|
||||||
if len(path) == len(cycle) - 1:
|
paths.append(distance)
|
||||||
paths.append(path_weight(G, path, weight="weight"))
|
|
||||||
|
|
||||||
|
|
||||||
def part_1() -> None:
|
def part_1() -> None:
|
||||||
|
|||||||
Reference in New Issue
Block a user