-
Notifications
You must be signed in to change notification settings - Fork 17
/
day15.py
executable file
·70 lines (50 loc) · 1.47 KB
/
day15.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
#!/usr/bin/env python3
import sys
import heapq
from math import inf as INFINITY
from collections import defaultdict
from itertools import filterfalse
def neighbors4(r, c, h, w):
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
rr, cc = (r + dr, c + dc)
if 0 <= rr < h and 0 <= cc < w:
yield rr, cc
def dijkstra(grid):
h, w = len(grid), len(grid[0])
source = (0, 0)
destination = (h - 1, w - 1)
queue = [(0, source)]
mindist = defaultdict(lambda: INFINITY, {source: 0})
visited = set()
while queue:
dist, node = heapq.heappop(queue)
if node == destination:
return dist
if node in visited:
continue
visited.add(node)
r, c = node
for neighbor in filterfalse(visited.__contains__, neighbors4(r, c, h, w)):
nr, nc = neighbor
newdist = dist + grid[nr][nc]
if newdist < mindist[neighbor]:
mindist[neighbor] = newdist
heapq.heappush(queue, (newdist, neighbor))
return INFINITY
# Open the first argument as input or use stdin if no arguments were given
fin = open(sys.argv[1]) if len(sys.argv) > 1 else sys.stdin
grid = list(list(map(int, row)) for row in map(str.rstrip, fin))
minrisk = dijkstra(grid)
print('Part 1:', minrisk)
tilew = len(grid)
tileh = len(grid[0])
for _ in range(4):
for row in grid:
tail = row[-tilew:]
row.extend((x + 1) if x < 9 else 1 for x in tail)
for _ in range(4):
for row in grid[-tileh:]:
row = [(x + 1) if x < 9 else 1 for x in row]
grid.append(row)
minrisk = dijkstra(grid)
print('Part 2:', minrisk)