Day 16 - Advent of Code 2024
16 December 2024
Working solutions for the day 16 puzzles.
Part One
""" day_16_01.py """
# usage: python3 day_16_01.py < input
import sys
from collections import deque
from collections import namedtuple
Point = namedtuple('GridPoint', 'x, y')
def ingest():
""" parse standard input """
def find(item):
""" where is it """
return [p for p, i in plan.items() if i == item][0]
plan = {}
x, y = 0, 0
with sys.stdin as infile:
for item in infile.read():
if item == '\n':
x, y = 0, y + 1
else:
plan[Point(x, y)] = item
x = x + 1
return find('S'), find('E'), plan
def route_scores(start, stop, plan):
""" calculate route scores through plan """
def adjacent(square, aim, tally):
""" adjacent squares """
output = set()
for dx, dy in [(0, -1), (1, 0), (0, 1), (-1, 0)]:
p = Point(square.x + dx, square.y + dy)
if plan.get(p, '#') != '#':
penalty = 1 if aim == (dx, dy) else 1001
output.add((p, (dx, dy), tally + penalty))
return output
scores = []
explore = deque([(start, (1, 0), 0)])
visited = {}
while explore:
tile, way, score = explore.popleft()
if tile == stop:
scores.append(score)
else:
tws = []
for t, w, s in adjacent(tile, way, score):
if visited.get((t, w), s) >= s:
visited[(t, w)] = s
tws.append((t, w, s))
explore.extend(tws)
return scores
begin, end, maze = ingest()
lowest_score = min(route_scores(begin, end, maze))
print(lowest_score)
Part Two