Advent-of-Code/2021/9/main2.py
David Vereb a31f009abe Day 9.
2021-12-09 16:53:29 -05:00

96 lines
2.6 KiB
Python

data = []
low_points = []
with open('data', 'r') as fp:
# NOTE(dev): We assume all lines are the same length
for line in fp:
data_line = []
for ch in line.strip():
data_line.append(int(ch))
data.append(data_line)
total = 0
for y in range(0, len(data)):
for x in range(0, len(data[y])):
sub_total = 0
all_four = 0
# above
if(y > 0):
if(data[y-1][x] > data[y][x]):
all_four += 1
else:
all_four += 1 # skip
# below
if(y < len(data) - 1):
if(data[y+1][x] > data[y][x]):
all_four += 1
else:
all_four += 1 #skip
# left
if(x > 0):
if(data[y][x-1] > data[y][x]):
all_four += 1
else:
all_four += 1 #skip
# right
if(x < len(data[y]) - 1):
if(data[y][x+1] > data[y][x]):
all_four += 1
else:
all_four += 1 #skip
if(all_four == 4):
total += data[y][x] + 1
low_points.append(tuple([y,x]))
print('Part 1:', total)
bin_sizes = []
for point in low_points:
points_to_check = [point]
checked_points = []
while len(points_to_check):
p = points_to_check.pop()
checked_points.append(p)
cur_y = p[0]
cur_x = p[1]
# check left
if(cur_x > 0):
if(data[cur_y][cur_x - 1] < 9):
left = tuple([cur_y, cur_x - 1])
if(not (left in checked_points) and not (left in points_to_check)):
points_to_check.append(left)
# check right
if(cur_x < len(data[0]) - 1):
if(data[cur_y][cur_x + 1] < 9):
right = tuple([cur_y, cur_x + 1])
if(not (right in checked_points) and not (right in points_to_check)):
points_to_check.append(right)
# check above
if(cur_y > 0):
if(data[cur_y - 1][cur_x] < 9):
above = tuple([cur_y - 1, cur_x])
if(not (above in checked_points) and not (above in points_to_check)):
points_to_check.append(above)
# check below
if(cur_y < len(data) - 1):
if(data[cur_y + 1][cur_x] < 9):
below = tuple([cur_y + 1, cur_x])
if(not (below in checked_points) and not (below in points_to_check)):
points_to_check.append(below)
bin_sizes.append(len(checked_points))
bin_sizes.sort()
total = 1
for i in range(len(bin_sizes) - 1, len(bin_sizes) - 4, -1):
total *= bin_sizes[i]
print(total)