advent2021/nine_second.py

34 lines
1.1 KiB
Python
Executable File

#!/usr/bin/env python3
from useful import *
def parseline(s):
return [int(c) for c in s]
with open(0) as f:
basegrid = np.asarray([parseline(l) for l in lines(f)])
grid = np.pad(basegrid, (1,1), constant_values=9)
is_nine = (grid == 9).astype('uint8')
mask = np.pad(is_nine, (1,1))
basins = []
for (x, y), _ in np.ndenumerate(is_nine):
if not is_nine[x, y]:
size, _, _, _ = cv.floodFill(is_nine, mask, (y, x), 1)
basins.append(size)
try:
if sys.argv[1] == '-v':
basin_water_ridge = (grid == 9).astype('uint8') + is_nine # 0, 1 or 2
palette = [(x & 255, x >> 8 & 255, x >> 16)
for x in [0x433c34, 0x7f9aa5, 0xae8c67]]
colored = np.transpose(np.asarray(np.vectorize(
lambda x: palette[x])(
basin_water_ridge)), axes=(1, 2, 0)).astype('uint8')
cv.imshow('basins', colored)
cv.waitKey(16)
except IndexError:
pass
print(np.prod(sorted(basins)[-3:]))