Twenty-Five Days · day 10 · both parts
Day 10: Hoof It
A friendly grid day. Part 1 is a textbook search, and part 2 is famous for being the answer people got by mistake while writing part 1. The interesting part is turning “walk every trail” into “count the trails”, which takes one decorator, or one loop over the heights.
The puzzle, in my words
A map gives a height from 0 to 9 in each cell. A trail starts on a 0 and climbs to a 9, going up exactly one with each step up, down, left or right. A trailhead is a 0 that starts at least one trail, and its score is how many different 9s it can reach. Add up the scores.
The example is an 8x8 map with nine trailheads. Their scores, in reading order, are 5, 6, 5, 3, 1, 3, 5, 3 and 5: 36 in all.
Part 1: how many summits
Step 1: a breadth-first search from every 0
From each 0, search outwards through neighbours exactly one higher, with a
seen set so each cell is entered once. Every 9 entered is a summit:
from collections import deque
def part1(text: str) -> int:
grid = [[int(ch) if ch.isdigit() else -1 for ch in line] for line in text.split()]
rows, cols = len(grid), len(grid[0])
total = 0
for r in range(rows):
for c in range(cols):
if grid[r][c] != 0:
continue
seen = {(r, c)}
queue = deque([(r, c)])
while queue:
y, x = queue.popleft()
if grid[y][x] == 9:
total += 1
continue
for ny, nx in ((y - 1, x), (y + 1, x), (y, x - 1), (y, x + 1)):
if (
0 <= ny < rows
and 0 <= nx < cols
and (ny, nx) not in seen
and grid[ny][nx] == grid[y][x] + 1
):
seen.add((ny, nx))
queue.append((ny, nx))
return total
The -1 is for the puzzle’s small examples, which mark some cells with .
so that no trail can enter them; real maps are all digits.
Since a trail goes up by exactly one per step, the cells at distance 3 from the trailhead are exactly the reachable 3s. A breadth-first search therefore sweeps the heights in order, one height per round, which is what the clip shows.
Step 2: complex numbers and dict.get
Store the map as a dict from position to height, with the position as a
complex number, column + row × 1j. The four neighbours are p + 1, p - 1,
p + 1j and p - 1j, and grid.get(q) returns None for a cell that is
off the map (or a ., which is simply left out), so the bounds checks go:
None is never equal to a height.
DIRS = (1, -1, 1j, -1j)
def parse(text: str) -> dict[complex, int]:
return {
complex(c, r): int(ch)
for r, line in enumerate(text.split())
for c, ch in enumerate(line)
if ch.isdigit()
}
def part1(text: str) -> int:
grid = parse(text)
total = 0
for start, h in grid.items():
if h != 0:
continue
seen = {start}
stack = [start]
while stack:
p = stack.pop()
for d in DIRS:
q = p + d
if grid.get(q) == grid[p] + 1 and q not in seen:
seen.add(q)
stack.append(q)
total += sum(grid[p] == 9 for p in seen)
return total
The deque became a plain list used as a stack, so this is now a depth-first
search. For reachability the order doesn’t matter: either way seen ends up
holding every cell some trail from this 0 can reach, and the score is the
number of 9s in it. sum over booleans counts the Trues, since True is
the integer 1.
It’s shorter, not faster. On a generated 50x50 map (the real size is my guess) step 1 takes about 1.6 ms and step 2 about 2.1 ms: building a dict with complex keys costs more than indexing lists.
Part 2: how many trails
Now each trailhead’s rating is the number of different trails that start on it. Two trails that end on the same 9 by different routes count separately. On the example the ratings are 20, 24, 10, 4, 1, 4, 5, 8 and 5: 81.
Step 1: the same search, without seen
Take step 2 of part 1 and delete the seen set. Heights only go up, so a
trail can’t loop back on itself, and every entry pushed on the stack is a
different trail so far. Each one that arrives at a 9 is one complete trail:
def part2(text: str) -> int:
grid = parse(text)
total = 0
for start, h in grid.items():
if h != 0:
continue
stack = [start]
while stack:
p = stack.pop()
if grid[p] == 9:
total += 1
continue
for d in DIRS:
if grid.get(p + d) == grid[p] + 1:
stack.append(p + d)
return total
That’s the whole of part 2, and several people in the public threads report that their first try at part 1 printed this number instead. It’s correct, but it walks every trail one by one, so its cost grows with the number of trails rather than the size of the map.
Step 2: count, and cache the counts
The trails from a cell are the trails from each of its neighbours one
higher, added together, and a 9 has exactly one trail: itself. That’s a
recursive function, and it gets asked about the same cells over and over,
because trails that meet share the rest of the climb. functools.cache
keeps each answer:
from functools import cache
def part2(text: str) -> int:
grid = parse(text)
@cache
def trails(p: complex) -> int:
h = grid[p]
if h == 9:
return 1
return sum(trails(p + d) for d in DIRS if grid.get(p + d) == h + 1)
return sum(trails(p) for p, h in grid.items() if h == 0)
Every cell is now worked out once at most, and the recursion is never more
than ten calls deep. Because trails is defined inside part2, each call of
part2 gets a fresh function and so a fresh cache.
Step 3: from the top down, no recursion
Step 2’s function only ever asks about cells one higher. So the counts can be filled in order, starting from the top: every 9 gets 1, then every 8 adds up its 9s, every 7 its 8s, and so on down to the 0s. That’s the same table the cache builds, filled bottom-up, which is dynamic programming in the textbook sense:
from collections import defaultdict
def part2(text: str) -> int:
grid = parse(text)
by_height = defaultdict(list)
for p, h in grid.items():
by_height[h].append(p)
ways = {p: 1 for p in by_height[9]}
for h in range(8, -1, -1):
for p in by_height[h]:
ways[p] = sum(ways[p + d] for d in DIRS if grid.get(p + d) == h + 1)
return sum(ways[p] for p in by_height[0])
When height h is being filled, every cell of height h + 1 already has an
entry in ways (possibly 0), so ways[p + d] is always there for the
neighbours the condition lets through.
This isn’t faster than step 2; it’s the same work in a fixed order. What it shows is why caching worked: the cells form layers, one per height, and each layer depends only on the one above it.
On a generated 50x50 map with clean hills (646 summits reached, 33,016 trails), step 1 takes about 28 ms while steps 2 and 3 take under 2 ms. On a noisier map with 2,469 trails it’s 4.5 ms against 1.3 and 1.7. Walking grows with the trails, counting with the cells. At this size all of them are quick.
All of this was checked on the puzzle’s examples and on generated inputs, not on a puzzle input of my own.