|
| 1 | +#! /usr/bin/env python3 |
| 2 | + |
| 3 | +def load_data(filename): |
| 4 | + with open(filename, 'r') as f: |
| 5 | + for line in f: |
| 6 | + line = line.rstrip('\n') |
| 7 | + t1 = line.split(' = ') |
| 8 | + t2 = t1[0].split(' to ') |
| 9 | + yield int(t1[1]), t2[0], t2[1] |
| 10 | + |
| 11 | +# Part One |
| 12 | + |
| 13 | +import itertools |
| 14 | +import networkx as nx |
| 15 | + |
| 16 | +G = nx.Graph() |
| 17 | + |
| 18 | +for distance, f, t in load_data('input.txt'): |
| 19 | + G.add_edge(f, t, weight=distance) |
| 20 | + |
| 21 | +def solve_shortest_hamiltonian_path(G): |
| 22 | + nodes = list(G.nodes) |
| 23 | + num_nodes = len(nodes) |
| 24 | + |
| 25 | + # Brute-force search over all permutations of nodes |
| 26 | + best_path = None |
| 27 | + min_cost = float("inf") |
| 28 | + |
| 29 | + for perm in itertools.permutations(nodes): # Try all orderings |
| 30 | + try: |
| 31 | + cost = sum(G[perm[i]][perm[i+1]]['weight'] for i in range(num_nodes - 1)) |
| 32 | + if cost < min_cost: |
| 33 | + min_cost = cost |
| 34 | + best_path = perm # This is the optimal open path |
| 35 | + except KeyError: |
| 36 | + # This catches cases where a path doesn't exist in non-complete graphs |
| 37 | + continue |
| 38 | + |
| 39 | + return best_path, min_cost |
| 40 | + |
| 41 | +path, cost = solve_shortest_hamiltonian_path(G) |
| 42 | + |
| 43 | +print(cost) |
| 44 | + |
| 45 | +# Part Two |
| 46 | + |
| 47 | +def solve_longest_hamiltonian_path(G): |
| 48 | + nodes = list(G.nodes) |
| 49 | + num_nodes = len(nodes) |
| 50 | + |
| 51 | + # Brute-force search over all permutations of nodes |
| 52 | + best_path = None |
| 53 | + max_cost = float("-inf") # Start with negative infinity |
| 54 | + |
| 55 | + for perm in itertools.permutations(nodes): # Try all orderings |
| 56 | + try: |
| 57 | + cost = sum(G[perm[i]][perm[i+1]]['weight'] for i in range(num_nodes - 1)) |
| 58 | + if cost > max_cost: # Maximization instead of minimization |
| 59 | + max_cost = cost |
| 60 | + best_path = perm # Store the best (longest) path |
| 61 | + except KeyError: |
| 62 | + # This catches cases where a path doesn't exist in non-complete graphs |
| 63 | + continue |
| 64 | + |
| 65 | + return best_path, max_cost |
| 66 | + |
| 67 | +path, cost = solve_longest_hamiltonian_path(G) |
| 68 | + |
| 69 | +print(cost) |
| 70 | + |
0 commit comments