|
3 | 3 | # Advent of Code 2025 Day 7 |
4 | 4 | # |
5 | 5 |
|
| 6 | +import itertools |
6 | 7 | import sys |
7 | 8 | from functools import cache |
8 | 9 |
|
|
13 | 14 | from aoc.grid import Cell |
14 | 15 | from aoc.grid import CharGrid |
15 | 16 |
|
16 | | -Input = InputData |
| 17 | +Input = CharGrid |
17 | 18 | Output1 = int |
18 | 19 | Output2 = int |
19 | 20 |
|
|
37 | 38 | ............... |
38 | 39 | """ |
39 | 40 |
|
| 41 | +SPLITTER = "^" |
| 42 | +START = "S" |
| 43 | + |
40 | 44 |
|
41 | 45 | class Solution(SolutionBase[Input, Output1, Output2]): |
42 | 46 | def parse_input(self, input_data: InputData) -> Input: |
43 | | - return input_data |
| 47 | + return CharGrid.from_strings(list(input_data)) |
44 | 48 |
|
45 | | - def part_1(self, inputs: Input) -> Output1: |
46 | | - grid = CharGrid.from_strings(list(inputs)) |
47 | | - beams = {next(grid.get_all_equal_to("S")).col} |
| 49 | + def part_1(self, grid: Input) -> Output1: |
| 50 | + beams = {next(grid.get_all_equal_to(START)).col} |
48 | 51 | ans = 0 |
49 | | - for sp in grid.get_all_equal_to("^"): |
| 52 | + for sp in grid.get_all_equal_to(SPLITTER): |
50 | 53 | if sp.col in beams: |
51 | 54 | ans += 1 |
52 | 55 | beams.remove(sp.col) |
53 | 56 | for d in (Direction.LEFT, Direction.RIGHT): |
54 | 57 | beams.add(sp.at(d).col) |
55 | 58 | return ans |
56 | 59 |
|
57 | | - def part_2(self, inputs: Input) -> Output2: |
58 | | - grid = CharGrid.from_strings(list(inputs)) |
59 | | - start = next(grid.get_all_equal_to("^")) |
60 | | - splitters = set(grid.get_all_equal_to("^")) | {start} |
| 60 | + def part_2(self, grid: Input) -> Output2: |
| 61 | + start = next(grid.get_all_equal_to(SPLITTER)) |
| 62 | + splitters = {start} | set(grid.get_all_equal_to(SPLITTER)) |
61 | 63 |
|
62 | 64 | @cache |
63 | 65 | def dfs(cell: Cell) -> int: |
64 | 66 | if cell == start: |
65 | 67 | return 1 |
66 | | - ans = 0 |
67 | | - for n in grid.get_cells_n(cell): |
68 | | - if n in splitters: |
69 | | - break |
70 | | - for d in (Direction.LEFT, Direction.RIGHT): |
71 | | - nxt = n.at(d) |
72 | | - if nxt in splitters: |
73 | | - ans += dfs(nxt) |
74 | | - return ans |
| 68 | + return sum( |
| 69 | + dfs(nxt) |
| 70 | + for nxt in ( |
| 71 | + n.at(d) |
| 72 | + for d in (Direction.LEFT, Direction.RIGHT) |
| 73 | + for n in itertools.takewhile( |
| 74 | + lambda n: n not in splitters, grid.get_cells_n(cell) |
| 75 | + ) |
| 76 | + ) |
| 77 | + if nxt in splitters |
| 78 | + ) |
75 | 79 |
|
76 | 80 | bottom_left = Cell(grid.get_max_row_index(), 0) |
77 | 81 | return dfs(bottom_left) + sum( |
|
0 commit comments