-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday18.py
80 lines (56 loc) · 1.78 KB
/
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
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
from collections import defaultdict, Counter, deque
from itertools import combinations, product, groupby
from re import findall
from heapq import *
from math import log10, ceil
def ints(it): return list(map(int, iter(it)))
def digits(n): return len(str(n)) # about 5% faster than doing a log10 approach for digits < 1e6
def part1(src):
w = 71
g = [[False for _ in range(w)] for _ in range(w)]
f = 1024
for i, l in enumerate(src.splitlines()):
if i >= f: break
x,y = ints(l.split(","))
g[y][x] = True
s = [(0, 0, 0)]
v = set()
# print("\n".join("".join("#" if x else "." for x in ys) for ys in g))
while s:
d,x,y = heappop(s)
if (x,y) in v:
continue
v.add((x,y))
if (x,y) == (w-1,w-1):
return d
for dx,dy in [(1,0),(-1,0),(0,1),(0,-1)]:
nx,ny = x+dx,y+dy
if 0 <= nx < w and 0 <= ny < w and not g[ny][nx]:
heappush(s, (d+1,nx,ny))
def part2(src):
w = 71
g = [[False for _ in range(w)] for _ in range(w)]
f = 1024
ls = src.splitlines()
for i, l in enumerate(ls):
if i >= f: break
x,y = ints(l.split(","))
g[y][x] = True
for l in ls[f:]:
x,y = ints(l.split(","))
g[y][x] = True
s = [(0, 0, 0)]
v = set()
while s:
d,x,y = heappop(s)
if (x,y) in v:
continue
v.add((x,y))
if (x,y) == (w-1,w-1):
break
for dx,dy in [(1,0),(-1,0),(0,1),(0,-1)]:
nx,ny = x+dx,y+dy
if 0 <= nx < w and 0 <= ny < w and not g[ny][nx]:
heappush(s, (d+1,nx,ny))
else:
return l