Twenty-Five Days · day 16 · both parts
Day 16: Reindeer Maze
A shortest-path day. The one idea that matters is what counts as a place in the search: not a tile, but a tile and the way you face on it. After that, part 1 is textbook Dijkstra, and part 2 is about not throwing away the ties.
The puzzle, in my words
A reindeer stands on S in a maze, facing east, and wants to get to E.
A step forward costs 1 point, and turning a quarter on the spot costs 1000;
walls can’t be walked into. Find the lowest score that gets it to E.
In the first example the best score is 7036: 7 turns and 36 steps. The second, bigger example comes to 11048, and its best route starts by turning north before taking a single step.
Part 1: the cheapest way through
Step 1: a queue that corrects itself
Since the cost of the next move depends on where the reindeer faces, a
state is (row, column, direction). Number the directions 0 to 3,
clockwise from east, and a quarter turn is d + 1 or d - 1, modulo 4.
Plain breadth-first search won’t do: with moves of 1 and 1000, the first time a state is reached isn’t necessarily the cheapest. A natural first fix is to remember the best score seen for every state, and put a state back on the queue whenever a cheaper way to it turns up. When the queue runs dry, nothing can be improved any more, and the end’s score is the answer:
from collections import deque
from math import inf
DIRS = [(0, 1), (1, 0), (0, -1), (-1, 0)] # east, south, west, north
EAST = 0
def part1(text: str) -> int:
grid = text.split()
for r, row in enumerate(grid):
for c, ch in enumerate(row):
if ch == "S":
start = (r, c, EAST)
elif ch == "E":
end = (r, c)
best = {start: 0}
queue = deque([start])
while queue:
r, c, d = queue.popleft()
cost = best[(r, c, d)]
dr, dc = DIRS[d]
moves = [
(r + dr, c + dc, d, cost + 1),
(r, c, (d + 1) % 4, cost + 1000),
(r, c, (d - 1) % 4, cost + 1000),
]
for nr, nc, nd, new_cost in moves:
if grid[nr][nc] != "#" and new_cost < best.get((nr, nc, nd), inf):
best[(nr, nc, nd)] = new_cost
queue.append((nr, nc, nd))
return min(best.get((*end, d), inf) for d in range(4))
The maze has a wall all the way round, so a step never leaves the grid and
there’s no bounds check. Turns are kept as their own moves rather than
folded into a 1001-point “turn and step”: that way a U-turn is simply two
turns, which matters if the only way out of S is behind the reindeer.
It is correct, but it can handle a state more than once. On a generated 141x141 maze (about the size reported for real inputs) it took about 85,000 states off the queue to settle about 40,000.
Step 2: Dijkstra
Take the cheapest state first instead, with a heap. Then each state is
expanded once, at its lowest score, and the first time E comes off the
heap, its score is the answer: everything still waiting costs at least as
much.
import heapq
def parse(text: str) -> tuple[list[str], tuple[int, int], tuple[int, int]]:
grid = text.split()
for r, row in enumerate(grid):
for c, ch in enumerate(row):
if ch == "S":
start = (r, c)
elif ch == "E":
end = (r, c)
return grid, start, end
def moves(grid: list[str], r: int, c: int, d: int):
dr, dc = DIRS[d]
if grid[r + dr][c + dc] != "#":
yield 1, r + dr, c + dc, d
yield 1000, r, c, (d + 1) % 4
yield 1000, r, c, (d - 1) % 4
def part1(text: str) -> int:
grid, start, end = parse(text)
heap = [(0, *start, EAST)]
done = set()
while heap:
cost, r, c, d = heapq.heappop(heap)
if (r, c) == end:
return cost
if (r, c, d) in done:
continue
done.add((r, c, d))
for step, nr, nc, nd in moves(grid, r, c, d):
if (nr, nc, nd) not in done:
heapq.heappush(heap, (cost + step, nr, nc, nd))
raise ValueError("no way from S to E")
The clip shows something specific to this puzzle. A turn costs 1000 and the example’s routes need far fewer than 1000 steps, so the heap hands out everything reachable with no turns, then everything with one turn, and so on: the score’s thousands are the turns and the rest is the steps.
Positions stay as integer tuples here, though complex numbers are tempting
for grids. heapq compares whole entries, so when two scores tie it goes on
to compare the positions, and complex numbers can’t be ordered: < between
two of them raises TypeError.
On the same generated maze the two steps took about the same time, around 50 ms each (the machine was busy with other work, so timings are rough), even though step 1 handles about twice as many states. Dijkstra’s real advantage here is the guarantee that each state is settled once, at its best score, and that is the shape part 2 builds on.
Part 2: every best path
Now count the tiles that lie on at least one lowest-score path, S and E
included. Several routes can tie, and their tiles all count, once each: 45
in the first example and 64 in the second.
Step 1: carry the path
The direct way: give every heap entry the list of tiles it walked, and let
a state be expanded again when it is reached at a score equal to its best,
not only better, so that tied paths all survive. Every path that reaches
E at the lowest score adds its tiles, and the search stops once the
heap’s scores go past that:
def part2(text: str) -> int:
grid, start, end = parse(text)
heap = [(0, *start, EAST, [start])]
best_at = {(*start, EAST): 0}
lowest = inf
tiles = set()
while heap:
cost, r, c, d, path = heapq.heappop(heap)
if cost > lowest:
break
if cost > best_at[(r, c, d)]:
continue
if (r, c) == end:
lowest = cost
tiles.update(path)
continue
for step, nr, nc, nd in moves(grid, r, c, d):
new_cost = cost + step
if new_cost <= best_at.get((nr, nc, nd), inf):
best_at[(nr, nc, nd)] = new_cost
new_path = path + [(nr, nc)] if (nr, nc) != (r, c) else path
heapq.heappush(heap, (new_cost, nr, nc, nd, new_path))
return len(tiles)
It’s right, and on the examples it’s instant. The trouble is that tied paths multiply: two ways round one block of wall, then two ways round the next, is four paths, each a separate entry with its own copy of the tiles. On generated 141x141 mazes it depends on how many loops there are. With each wall between two open tiles knocked out with a 5% chance, it took about 0.3 s; at 15%, about 9 s; at 30%, I stopped it after three minutes. How loopy the real inputs are couldn’t be checked here, so this says how the method scales, not whether it finishes on a real input.
Step 2: remember where each state came from
The paths overlap, so store the overlap once. Run Dijkstra as in part 1,
but for every state keep a list of the states it was reached from at its
lowest score: start a new list when a cheaper way turns up, and add to it
on a tie. When the search is done, follow those links backwards from E
(from each direction that arrives at the lowest score) and collect every
state the walk touches. Those are exactly the states on some best path:
from collections import defaultdict
def part2(text: str) -> int:
grid, start, end = parse(text)
first = (*start, EAST)
best_at = {first: 0}
came_from = defaultdict(list)
heap = [(0, *first)]
lowest = inf
while heap:
cost, r, c, d = heapq.heappop(heap)
if cost > lowest:
break
if cost > best_at[(r, c, d)]:
continue # stale: this state was reached more cheaply since
if (r, c) == end:
lowest = cost
continue
for step, nr, nc, nd in moves(grid, r, c, d):
new_cost = cost + step
old = best_at.get((nr, nc, nd), inf)
if new_cost < old:
best_at[(nr, nc, nd)] = new_cost
came_from[(nr, nc, nd)] = [(r, c, d)]
heapq.heappush(heap, (new_cost, nr, nc, nd))
elif new_cost == old:
came_from[(nr, nc, nd)].append((r, c, d))
stack = [(*end, d) for d in range(4) if best_at.get((*end, d)) == lowest]
on_best = set(stack)
while stack:
for prev in came_from[stack.pop()]:
if prev not in on_best:
on_best.add(prev)
stack.append(prev)
return len({(r, c) for r, c, _ in on_best})
Each state is expanded once and nothing is copied. The links of a state are complete by the time it comes off the heap, because every move costs something: anything that could still reach it at the same score would have to come from a cheaper state, and those have all been handled. On the generated mazes this took 60 to 80 ms, the loopiest one included.
The link lists are on states, not tiles, and that matters. The same tile can be on a best path facing north and off it facing east; keeping only the tile would mix the two up.
Another way, used in the tests as a cross-check rather than here: run one
search forwards from S and one backwards from E (all four directions at
E, steps reversed), and a state is on a best path when its two scores add
up to the lowest. That comparison too has to be per state, not per tile.
All of this was checked on the puzzle’s two examples, on a brute force that tries every path in small mazes, and on generated mazes, not on a puzzle input of my own.