|
| 1 | +from collections import deque |
| 2 | +from typing import Iterable |
| 3 | +from pathlib import Path |
| 4 | + |
| 5 | +Grid = list[list[int]] |
| 6 | +Point = tuple[int, int] |
| 7 | + |
| 8 | + |
| 9 | +def parse_input() -> Grid: |
| 10 | + return [ |
| 11 | + [int(col) for col in row] |
| 12 | + for row in (Path(__file__).parent / "input.txt").read_text().splitlines() |
| 13 | + ] |
| 14 | + |
| 15 | + |
| 16 | +def neighbours(point: Point, grid: Grid) -> Iterable[Point]: |
| 17 | + |
| 18 | + for x, y in [ |
| 19 | + (0, -1), |
| 20 | + (1, -1), |
| 21 | + (1, 0), |
| 22 | + (1, 1), |
| 23 | + (0, 1), |
| 24 | + (-1, 1), |
| 25 | + (-1, 0), |
| 26 | + (-1, -1), |
| 27 | + ]: |
| 28 | + nx = point[0] + x |
| 29 | + ny = point[1] + y |
| 30 | + if not 0 <= nx < len(grid): |
| 31 | + continue |
| 32 | + if not 0 <= ny < len(grid): |
| 33 | + continue |
| 34 | + yield (nx, ny) |
| 35 | + |
| 36 | + |
| 37 | +def solve() -> None: |
| 38 | + grid = parse_input() |
| 39 | + flashes = 0 |
| 40 | + flashes_at_step = [] |
| 41 | + |
| 42 | + while True: |
| 43 | + |
| 44 | + need_to_flash = deque() |
| 45 | + |
| 46 | + for y in range(len(grid)): |
| 47 | + for x in range(len(grid[y])): |
| 48 | + grid[y][x] += 1 |
| 49 | + if grid[y][x] > 9: |
| 50 | + need_to_flash.append((x, y)) |
| 51 | + |
| 52 | + flashed = set() |
| 53 | + while need_to_flash: |
| 54 | + x, y = need_to_flash.popleft() |
| 55 | + if (x, y) in flashed: |
| 56 | + continue |
| 57 | + flashed.add((x, y)) |
| 58 | + for nx, ny in neighbours((x, y), grid): |
| 59 | + grid[ny][nx] += 1 |
| 60 | + if grid[ny][nx] > 9 and (nx, ny) not in flashed: |
| 61 | + need_to_flash.append((nx, ny)) |
| 62 | + flashes += len(flashed) |
| 63 | + flashes_at_step.append(flashes) |
| 64 | + |
| 65 | + for y in range(len(grid)): |
| 66 | + for x in range(len(grid[y])): |
| 67 | + if grid[y][x] > 9: |
| 68 | + grid[y][x] = 0 |
| 69 | + |
| 70 | + if len(flashed) == len(grid) ** 2: |
| 71 | + break |
| 72 | + |
| 73 | + # First part |
| 74 | + assert flashes_at_step[100] == 1739 |
| 75 | + |
| 76 | + # Second part |
| 77 | + assert len(flashes_at_step) == 324 |
| 78 | + |
| 79 | + |
| 80 | +if __name__ == "__main__": |
| 81 | + solve() |
0 commit comments