-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathday09.py
More file actions
72 lines (52 loc) · 1.34 KB
/
day09.py
File metadata and controls
72 lines (52 loc) · 1.34 KB
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
import operator as op
import functools
def parse(input):
ret = {}
for y, line in enumerate(input.strip().splitlines()):
for x, val in enumerate(line):
ret[(x, y)] = int(val)
return ret
def neighbors(p):
return [
(p[0]+1, p[1]),
(p[0]-1, p[1]),
(p[0], p[1]+1),
(p[0], p[1]-1)
]
def low_point(p, input):
return all(input[p] < input.get(np, 9) for np in neighbors(p))
def basin_size(p, input, checked):
if p in checked:
return 0
if input.get(p, 9) == 9:
return 0
checked.add(p)
size = 1
for np in neighbors(p):
size += basin_size(np, input, checked)
return size
def part1(input):
input = parse(input)
ret = 0
for p in input:
if low_point(p, input):
ret += input[p] + 1
return ret
def part2(input):
input = parse(input)
checked = set()
basins = []
for p in input:
if p in checked:
continue
basins.append(basin_size(p, input, checked))
basins.sort(reverse=True)
return functools.reduce(op.mul, basins[:3])
if __name__ == '__main__':
import sys
import utils
input = sys.stdin.read()
p1, t1 = utils.time(part1, input)
print(f'part1: {p1} ({t1:0.20f})')
p2, t2 = utils.time(part2, input)
print(f'part2: {p2} ({t2:.20f})')