+/AoC

advent of code

git clone https://git.julia.blue/+/AoC

Joseph RyanDay 99a286d3

master
908 B36 linesraw
1from operator import mul
2from functools import reduce as fold
3
4grid = [[int(c) for c in line.strip()] for line in open("input").readlines()]
5h = len(grid)
6w = len(grid[0])
7
8
9def fill(x, y, v):
10    if not (0 <= x < w and 0 <= y < h) or grid[y][x] == 9 or v[y][x]:
11        return 0
12    v[y][x] = True
13    return (
14        1
15        + fill(x, y + 1, v)
16        + fill(x, y - 1, v)
17        + fill(x + 1, y, v)
18        + fill(x - 1, y, v)
19    )
20
21
22total = 0
23basins = []
24for y in range(h):
25    for x in range(w):
26        n = grid[y][x]
27        if (
28            (y == 0 or n < grid[y - 1][x])
29            and (y == h - 1 or n < grid[y + 1][x])
30            and (x == 0 or n < grid[y][x - 1])
31            and (x == w - 1 or n < grid[y][x + 1])
32        ):
33            total += n + 1
34            basins.append(fill(x, y, [[False for _ in range(w)] for _ in range(h)]))
35print(total)
36print(fold(mul, sorted(basins)[-3:]))