← blog

Twenty-Five Days · day 18 · both parts

Day 18: RAM Run

the puzzle ↗ #aoc-2024#python

A shortest-path day, and the shortest path is the easy half. Part 2 asks the same question thousands of times, and the fun is in how few of those questions you actually need to ask.

The puzzle, in my words

A list of grid cells arrives in order; each one becomes a wall when it lands. The grid is 71x71 (7x7 in the example), you start in the top-left corner, the exit is in the bottom-right, and you move one cell up, down, left or right at a time. After the first 1024 cells have landed (12 in the example), how many moves does the shortest route take? In the example it’s 22.

The functions below take the grid size as a parameter (default 71), and part 1’s also take the number of bytes (default 1024), so the tests can pass 7 and 12.

Part 1: the shortest route

Part 1 on the example: twelve bytes land, then the search spreads one step at a time and the route is traced back.

Every move costs the same, so a breadth-first search finds the fewest: a queue of cells to visit and a dict of the distance to each cell seen so far. Cells come off the queue in order of distance, so the first time the exit comes off, its distance is the answer.

from collections import deque


def parse(text: str) -> list[tuple[int, int]]:
    return [tuple(map(int, line.split(","))) for line in text.split()]


def shortest(walls: set[tuple[int, int]], size: int) -> int | None:
    goal = (size - 1, size - 1)
    dist = {(0, 0): 0}
    queue = deque([(0, 0)])
    while queue:
        x, y = queue.popleft()
        if (x, y) == goal:
            return dist[(x, y)]
        for nx, ny in ((x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)):
            if 0 <= nx < size and 0 <= ny < size and (nx, ny) not in walls and (nx, ny) not in dist:
                dist[(nx, ny)] = dist[(x, y)] + 1
                queue.append((nx, ny))
    return None


def part1(text: str, size: int = 71, count: int = 1024) -> int | None:
    return shortest(set(parse(text)[:count]), size)

A cell gets its distance when it’s first put on the queue, not when it’s taken off, so it is never queued twice. deque.popleft() is cheap where list.pop(0) has to shift the whole list along.

Step 2: a ring at a time, with sets

The clip shows the search as rings: every cell at distance 0, then every cell at distance 1, and so on. That can be the code too. Keep the set of free cells, and the frontier, the cells at the current distance. The next frontier is their neighbours that are still free; taking each frontier out of free stops the search coming back.

DIRS = (1, -1, 1j, -1j)


def ring_search(walls: set[complex], size: int) -> int | None:
    free = {complex(x, y) for x in range(size) for y in range(size)} - walls
    goal = complex(size - 1, size - 1)
    frontier = {0j} & free
    steps = 0
    while frontier:
        if goal in frontier:
            return steps
        free -= frontier
        frontier = {p + d for p in frontier for d in DIRS} & free
        steps += 1
    return None


def part1(text: str, size: int = 71, count: int = 1024) -> int | None:
    walls = {complex(x, y) for x, y in parse(text)[:count]}
    return ring_search(walls, size)

A cell is the complex number x + y*1j, so a neighbour is p + d, and the intersection with free is the bounds check and the wall check in one. No queue and no distance dict: the loop counter is the distance. On a generated 71x71 input with 1024 walls (more on it below), the two take 3.6 ms and 2.7 ms. That’s a small difference, and the machine was busy, so I wouldn’t read much into it. I keep step 2 for being shorter and for matching the picture.

Part 2: the byte that cuts it off

Keep dropping bytes. Which one is the first to leave no route at all? The answer is that byte’s position, written X,Y: in the example, the path survives the 20th byte (at 1,1) and the 21st, at 6,1, cuts it.

Part 2 on the example: search again only when a byte lands on the path. At the end, the red chain of walls is what step 4 looks for.

Step 1: search after every byte

The direct way: add the bytes one at a time and run the step 1 search after each, until it finds nothing.

def part2(text: str, size: int = 71) -> str | None:
    walls = set()
    for x, y in parse(text):
        walls.add((x, y))
        if shortest(walls, size) is None:
            return f"{x},{y}"
    return None

It’s correct, and it’s one full search per byte. On the generated input (3,450 bytes, cut off at byte 1,679) that is 4.9 seconds.

Step 2: only when the path is hit

Most bytes can’t matter. If a byte lands anywhere off the route we already have, that route still works, so there is nothing to check. Only a byte on the route needs a new search. For that the search has to hand back the route, so it remembers where it reached each cell from and walks back from the exit.

def path(walls: set[tuple[int, int]], size: int) -> set[tuple[int, int]] | None:
    goal = (size - 1, size - 1)
    came_from = {(0, 0): None}
    queue = deque([(0, 0)])
    while queue:
        x, y = queue.popleft()
        if (x, y) == goal:
            cells, cell = set(), goal
            while cell is not None:
                cells.add(cell)
                cell = came_from[cell]
            return cells
        for nx, ny in ((x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)):
            if (
                0 <= nx < size
                and 0 <= ny < size
                and (nx, ny) not in walls
                and (nx, ny) not in came_from
            ):
                came_from[(nx, ny)] = (x, y)
                queue.append((nx, ny))
    return None


def part2(text: str, size: int = 71) -> str | None:
    walls = set()
    route = path(walls, size)
    for x, y in parse(text):
        walls.add((x, y))
        if (x, y) in route:
            route = path(walls, size)
            if route is None:
                return f"{x},{y}"
    return None

In the example, only two of the nine bytes from the 13th to the 21st hit the path: the 13th and the 21st. On the generated input, 55 of the first 1,679 bytes did, and the time drops to about 160 ms. How many bytes hit the path depends on the input, and I couldn’t check how real inputs are laid out, so I can’t say how this step fares on them.

Turn the question round: after how many bytes is the exit cut off? The answer is no, no, no, …, yes, yes, yes, because walls are never removed: once blocked, always blocked. A sorted run of False then True is what binary search is for, and bisect can do it with a key:

from bisect import bisect_left


def part2(text: str, size: int = 71) -> str | None:
    falling = parse(text)

    def blocked(n: int) -> bool:
        return ring_search({complex(x, y) for x, y in falling[:n]}, size) is None

    n = bisect_left(range(len(falling) + 1), True, key=blocked)
    if n > len(falling):
        return None
    x, y = falling[n - 1]
    return f"{x},{y}"

bisect_left has taken key= since Python 3.10. The key is applied to the items (here, byte counts) but not to the value being searched for, which is why that value is True and not a count. A range works as the sequence because it supports len and indexing without building a list. n is the smallest count that blocks, so the culprit is byte n - 1, counting from 0. That’s about a dozen searches for 3,450 bytes, 22 ms on the generated input.

Step 4: watch the walls instead

There’s a way to need no search at all. Look at the final frame of the clip: the route is cut exactly when the walls form a chain from the top or right edge to the bottom or left edge. Walls count as touching corner to corner as well as side by side, because moving only up, down, left and right you can’t squeeze between two walls that meet at a corner. The chain has the start on one side and the exit on the other.

So keep the chains of walls in a union-find. Two extra nodes stand for the two stretches of edge, and each byte joins its neighbours (all eight) and any edge it touches. The first byte that puts both edge nodes in the same set is the answer.

def part2(text: str, size: int = 71) -> str | None:
    parent = {"top-right": "top-right", "bottom-left": "bottom-left"}

    def find(a):
        while parent[a] != a:
            parent[a] = parent[parent[a]]  # path halving
            a = parent[a]
        return a

    def union(a, b):
        parent[find(a)] = find(b)

    for x, y in parse(text):
        parent.setdefault((x, y), (x, y))
        if y == 0 or x == size - 1:
            union((x, y), "top-right")
        if x == 0 or y == size - 1:
            union((x, y), "bottom-left")
        for dx in (-1, 0, 1):
            for dy in (-1, 0, 1):
                if (x + dx, y + dy) in parent:
                    union((x, y), (x + dx, y + dy))
        if find("top-right") == find("bottom-left"):
            return f"{x},{y}"
    return None

The cells are tuples and the edge nodes strings, so they share one dict without clashing, and a cell that isn’t a wall simply isn’t in it. Each byte is a handful of unions, and it reads the bytes once, stopping at the cut: 3.7 ms on the generated input, against 4.9 seconds for step 1. A corner byte needs no special case: a wall on the start touches the top and the left edge, so it joins the two nodes at once, which is right. Steps 1 and 2 would miss that one, because their search sets off from the start whether it’s a wall or not. The example has no byte on a corner, and the random tests leave the corners out for that reason.

There’s a mirror version: start with every byte fallen, then take them away from the last one backwards, joining open cells, until the start and the exit are in one set. It works too, but it needs the whole list before it starts, where this one stops at the cut.

The tests run every step of each part against the first one on 300 random grids, from 2x2 to 12x12, with every cell except the two corners falling in a random order. The generated input for the timings is 3,450 such cells on a 71x71 grid, about the length real inputs are said to have. Its bytes fall uniformly at random, and real inputs may well not, so take the timings as a rough comparison of the steps, measured on a busy machine.

All of this was checked on the puzzle’s example and on generated inputs, not on a puzzle input of my own.