|
| 1 | +from collections import deque |
| 2 | + |
| 3 | +from . import SeparateRunner |
| 4 | + |
| 5 | + |
| 6 | +def parse_input(data: str) -> list[tuple[int, int]]: |
| 7 | + return [tuple(map(int, line.split(","))) for line in data.strip().split("\n")] |
| 8 | + |
| 9 | + |
| 10 | +def find_exit(fallen: set[tuple[int, int]], width: int, height: int) -> int | None: |
| 11 | + todo = deque([(0, 0, 0)]) |
| 12 | + |
| 13 | + best = {(0, 0): 0} |
| 14 | + |
| 15 | + def enqueue(dist: int, x: int, y: int): |
| 16 | + # print(f"trying {x},{y}") |
| 17 | + if (x, y) in fallen: |
| 18 | + return |
| 19 | + |
| 20 | + if (x, y) not in best or best[x, y] > dist: |
| 21 | + best[x, y] = dist |
| 22 | + todo.append((dist, x, y)) |
| 23 | + |
| 24 | + while todo: |
| 25 | + dist, x, y = todo.popleft() |
| 26 | + # print(x, y) |
| 27 | + |
| 28 | + if x == width - 1 and y == height - 1: |
| 29 | + return dist |
| 30 | + |
| 31 | + if x > 0: |
| 32 | + enqueue(dist + 1, x - 1, y) |
| 33 | + |
| 34 | + if x + 1 < width: |
| 35 | + enqueue(dist + 1, x + 1, y) |
| 36 | + |
| 37 | + if y > 0: |
| 38 | + enqueue(dist + 1, x, y - 1) |
| 39 | + |
| 40 | + if y + 1 < height: |
| 41 | + enqueue(dist + 1, x, y + 1) |
| 42 | + |
| 43 | + |
| 44 | +class DayRunner(SeparateRunner): |
| 45 | + @classmethod |
| 46 | + def part1( |
| 47 | + cls, input: str, width: int = 71, height: int = 71, limit: int = 1024 |
| 48 | + ) -> int: |
| 49 | + falling = parse_input(input) |
| 50 | + |
| 51 | + return find_exit(set(falling[:limit]), width, height) |
| 52 | + |
| 53 | + @classmethod |
| 54 | + def part2(cls, input: str, width: int = 71, height: int = 71) -> str: |
| 55 | + falling = parse_input(input) |
| 56 | + |
| 57 | + lower = 0 |
| 58 | + upper = len(falling) |
| 59 | + |
| 60 | + while lower < upper: |
| 61 | + mid = lower + (upper - lower) // 2 |
| 62 | + |
| 63 | + if find_exit(set(falling[:mid]), width, height) is not None: |
| 64 | + lower = mid + 1 |
| 65 | + else: |
| 66 | + upper = mid |
| 67 | + |
| 68 | + first_blocker = falling[lower - 1] |
| 69 | + |
| 70 | + return f"{first_blocker[0]},{first_blocker[1]}" |
0 commit comments