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
|
import sys
from collections import defaultdict, Counter, deque
data = sys.argv[1] if len(sys.argv) > 1 else "day9data.txt"
G = []
for line in open(data):
G.append([int(x) for x in list(line.strip())])
R = len(G)
C = len(G[0])
DR = [-1, 0, 1, 0]
DC = [0, 1, 0, -1]
ans = 0
for r in range(R):
assert len(G[r]) == C
for c in range(C):
ok = True
for d in range(4):
rr = r + DR[d]
cc = c + DC[d]
if 0 <= rr < R and 0 <= cc < C and G[rr][cc] <= G[r][c]:
ok = False
if ok:
ans += G[r][c] + 1
print(ans)
S = []
SEEN = set()
for r in range(R):
for c in range(C):
if (r, c) not in SEEN and G[r][c] != 9:
size = 0
Q = deque()
Q.append((r, c))
while Q:
(r, c) = Q.popleft()
if (r, c) in SEEN:
continue
SEEN.add((r, c))
size += 1
for d in range(4):
rr = r + DR[d]
cc = c + DC[d]
if 0 <= rr < R and 0 <= cc < C and G[rr][cc] != 9:
Q.append((rr, cc))
S.append(size)
S.sort()
print(S[-1] * S[-2] * S[-3])
|