advent-of-code/2025-python/output/day_07.py
Anders Englöf Ytterström 8683885438 Solve 2025 day 7 pt 1-2
For part 1, BFS is used since there is no need to
visit each splitter more than once to count visited
splitters.

For part 2, the code initially removed the visited
check. This failed miserably, losing momentum aound
Y=54-56.

A recursive function with memoization solves it much
faster.
2025-12-10 00:34:12 +01:00

50 lines
1 KiB
Python

import functools
from output import grid
def solve(data):
G = grid(data, o="^")
p1 = set()
p2 = 0
H = len(data.split())
W = len(data.split()[0])
S = (0, data.split()[0].index("S"))
Q = [S]
while Q:
y, x = Q.pop(0)
if y == H:
continue
if (y, x) in p1:
continue
if (y, x) in G:
Q.append((y, x - 1))
Q.append((y, x + 1))
p1.add((y, x))
else:
Q.append((y + 1, x))
p1 = len(p1)
@functools.cache
def _timelines(p):
y, x = p
if not 0 <= y < H or not 0 <= x < W:
return 1
if p in G:
return _timelines((y, x - 1)) + _timelines((y, x + 1))
return _timelines((y + 1, x))
p2 = _timelines(S)
return p1, p2
if __name__ == "__main__":
with open("./input/07.txt", "r") as f:
inp = f.read().strip()
p1, p2 = solve(inp)
print(p1)
print(p2)
assert p1 == 1539
assert p2 == 6479180385864