-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpart2.py
36 lines (26 loc) · 1.23 KB
/
part2.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
with open("input.txt") as file:
heightmap = [list(map(int, line.strip())) for line in file]
n, m = len(heightmap), len(heightmap[0])
visited = tuple([False] * m for _ in range(n))
def search_basin(i, j):
if heightmap[i][j] == 9 or visited[i][j]:
return 0
visited[i][j] = True
return 1 + sum((
0 if j == 0 or heightmap[i][j] >= heightmap[i][j - 1] else search_basin(i, j - 1), # left
0 if i == 0 or heightmap[i][j] >= heightmap[i - 1][j] else search_basin(i - 1, j), # up
0 if i == n - 1 or heightmap[i][j] >= heightmap[i + 1][j] else search_basin(i + 1, j), # right
0 if j == m - 1 or heightmap[i][j] >= heightmap[i][j + 1] else search_basin(i, j + 1) # down
))
basin_sizes = []
for i in range(n):
for j in range(m):
if all((
j == 0 or heightmap[i][j] < heightmap[i][j - 1], # left
i == 0 or heightmap[i][j] < heightmap[i - 1][j], # up
i == n - 1 or heightmap[i][j] < heightmap[i + 1][j], # right
j == m - 1 or heightmap[i][j] < heightmap[i][j + 1] # down
)):
basin_sizes.append(search_basin(i, j))
basin_sizes.sort()
print(basin_sizes.pop() * basin_sizes.pop() * basin_sizes.pop())