-
Notifications
You must be signed in to change notification settings - Fork 0
/
24.py
80 lines (45 loc) · 1.21 KB
/
24.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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
from lib import *
input = read_input(2016, 24)
grid = input.splitlines()
nodes = {}
rnodes = {}
for i, line in enumerate(grid):
for j, c in enumerate(line):
if c.isnumeric():
nodes[int(c)] = j, i
rnodes[(j, i)] = int(c)
def asp(x, y):
queue = [(0, x, y)]
out = {}
visited = set()
while queue:
d, x, y = queue.pop(0)
if (x, y) in visited:
continue
visited.add((x, y))
if (x, y) in rnodes:
out[rnodes[(x, y)]] = d
for p, q in [(x, y - 1), (x, y + 1), (x - 1, y), (x + 1, y)]:
if p not in range(len(grid[0])) or q not in range(len(grid)) or grid[q][p] == "#":
continue
queue.append((d + 1, p, q))
return out
sp = {k: asp(*v) for k, v in nodes.items()}
best = 1e1337
for order in itertools.permutations(set(sp) - {0}):
pos = 0
cost = 0
for x in order:
cost += sp[pos][x]
pos = x
best = min(best, cost)
print(best)
best = 1e1337
for order in itertools.permutations(set(sp) - {0}):
pos = 0
cost = 0
for x in order:
cost += sp[pos][x]
pos = x
best = min(best, cost + sp[pos][0])
print(best)