-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathday18.py
48 lines (32 loc) · 911 Bytes
/
day18.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
data = open(0).read().splitlines()
inp = [(*map(int, line.split(",")),) for line in data]
grid = {v: i for i, v in enumerate(inp)}
m = max(max(x, y) for x, y in inp)
start = (0, 0)
end = (m, m)
def bfs(tl):
q = [(start, 0)]
visited = set()
while q:
(x, y), d = q.pop(0)
if (x, y) == end:
return d
if (x, y) in visited:
continue
visited.add((x, y))
for dx, dy in (-1, 0), (1, 0), (0, -1), (0, 1):
nx, ny = x + dx, y + dy
if 0 <= nx <= m and 0 <= ny <= m and grid.get((nx, ny), tl) >= tl:
q.append(((nx, ny), d + 1))
def part1():
return bfs(1024 if m == 70 else 12)
def part2():
lo, hi = 0, len(data)
while lo < hi:
if bfs(mid := (lo + hi) // 2):
lo = mid + 1
else:
hi = mid
return data[lo - 1]
print(part1())
print(part2())