50 lines
1.4 KiB
Python
50 lines
1.4 KiB
Python
grid = []
|
|
to_flash = []
|
|
|
|
for line in open('data', 'r'):
|
|
grid_line = []
|
|
for ch in line.strip():
|
|
grid_line.append(int(ch))
|
|
grid.append(grid_line)
|
|
|
|
flashed = 0
|
|
step = 0
|
|
#for step in range(0, 100):
|
|
while(True):
|
|
# Step 1: Increment
|
|
for y in range(0, len(grid)):
|
|
for x in range(0, len(grid[y])):
|
|
grid[y][x] += 1
|
|
if(grid[y][x] > 9):
|
|
to_flash.append(tuple([y, x]))
|
|
|
|
# Step 2: Flash
|
|
prior_flash = flashed
|
|
while(len(to_flash)):
|
|
cell = to_flash[-1] # take the last one
|
|
to_flash.pop() # remove
|
|
flashed += 1 # count
|
|
for y in range(-1, 2):
|
|
new_y = cell[0] + y
|
|
if(new_y >= 0 and new_y < len(grid)): # in bounds
|
|
for x in range(-1, 2):
|
|
new_x = cell[1] + x
|
|
if(new_x >= 0 and new_x < len(grid[y])): # in bounds
|
|
grid[new_y][new_x] += 1
|
|
if(grid[new_y][new_x] == 10): # JUST flashed
|
|
to_flash.append(tuple([new_y, new_x]))
|
|
|
|
# PART TWO ANSWER
|
|
if(flashed - prior_flash == len(grid) * len(grid[0])):
|
|
print('all flash step #', step + 1)
|
|
break
|
|
|
|
# Step 3: Reset (if flashed)
|
|
for y in range(0, len(grid)):
|
|
for x in range(0, len(grid[y])):
|
|
if(grid[y][x] > 9):
|
|
grid[y][x] = 0
|
|
|
|
print('Step #', (step + 1), ': ', flashed)
|
|
step += 1
|