← blog

Twenty-Five Days · day 15 · both parts

Day 15: Warehouse Woes

the puzzle ↗ #aoc-2024#python

A simulation day. Part 1 is a robot pushing rows of boxes, and the only trick is seeing how little of the row actually changes. Part 2 makes the boxes two cells wide, which turns a row into a tree, and the interesting part is the order: find everything that would move, and only then move it.

The puzzle, in my words

A map of a warehouse shows walls (#), boxes (O), empty floor (.) and a robot (@). Under it is a long list of moves, ^ v < >, split over several lines just for convenience. The robot tries each move in turn. Any boxes directly in its way get pushed along, a whole row at once, but if the row would run into a wall, nothing moves at all, robot included.

When the moves are done, each box scores 100 times its row plus its column (counted from the map’s top-left corner, walls included), its GPS coordinate. The answer is the sum. The small example, an 8x8 map with 15 moves, sums to 2028; a larger 10x10 one with 700 moves sums to 10092.

Part 1: pushing a row of boxes

Part 1 on the small example, every move. Pink: the boxes the robot would push; a red wall means the move does nothing.

Step 1: the first version

Split the input at the blank line and glue the move lines back together. Keep the map as a list of lists. For a move, walk away from the robot while the cells hold boxes. If the first cell that isn’t a box is a wall, skip the move. Otherwise it’s empty, so shift every cell of the row one place along, starting from the far end so nothing is overwritten before it is copied:

MOVES = {"^": (-1, 0), "v": (1, 0), "<": (0, -1), ">": (0, 1)}


def split_input(text: str) -> tuple[list[str], str]:
    top, bottom = text.strip().split("\n\n")
    return top.split(), "".join(bottom.split())


def part1(text: str) -> int:
    rows, moves = split_input(text)
    grid = [list(row) for row in rows]
    for r, row in enumerate(grid):
        for c, ch in enumerate(row):
            if ch == "@":
                robot = (r, c)
    for m in moves:
        dr, dc = MOVES[m]
        r, c = robot[0] + dr, robot[1] + dc
        while grid[r][c] == "O":
            r, c = r + dr, c + dc
        if grid[r][c] == "#":
            continue
        while (r, c) != robot:
            grid[r][c] = grid[r - dr][c - dc]
            r, c = r - dr, c - dc
        grid[r][c] = "."
        robot = (r + dr, c + dc)
    return sum(100 * r + c for r, row in enumerate(grid) for c, ch in enumerate(row) if ch == "O")

The map is walled all round, so the walk always meets a # before it could leave the grid, and there’s no bounds check.

Step 2: only the ends of the row change

Look at what a push does to the map. The robot steps into the first box’s cell, and the empty cell past the last box fills with a box. Every box in between is replaced by an identical box, so as far as the map can tell, it didn’t move. One box moving from the near end to the far end is the whole push.

That suggests a different representation: walls and boxes as sets of positions, with each position a complex number, column + row × 1j, so a move is an addition. The push becomes one remove and one add:

STEPS = {"^": -1j, "v": 1j, "<": -1, ">": 1}


def part1(text: str) -> int:
    rows, moves = split_input(text)
    walls, boxes = set(), set()
    for r, row in enumerate(rows):
        for c, ch in enumerate(row):
            p = complex(c, r)
            if ch == "#":
                walls.add(p)
            elif ch == "O":
                boxes.add(p)
            elif ch == "@":
                robot = p
    for m in moves:
        d = STEPS[m]
        end = robot + d
        while end in boxes:
            end += d
        if end in walls:
            continue
        robot += d
        if end != robot:
            boxes.remove(robot)
            boxes.add(end)
    return int(sum(100 * p.imag + p.real for p in boxes))

The if end != robot covers a move with no box in the way: then the walk stops at once, end is where the robot steps, and only the robot moves. p.real and p.imag are floats (a complex number always holds two), hence the int at the end; whole numbers this small are exact as floats.

This isn’t faster in practice. On a generated 50x50 map with 20,000 random moves, both versions take about 4 ms. On that map only 2,677 of the moves push anything, and those push 1.6 boxes on average (13 at most), so there’s little to save. It’s shorter, and there’s less to get wrong.

Part 2: boxes two cells wide

Now the map is twice as wide: every wall becomes ##, every box [], every empty cell .., and the robot @., so the robot is still one cell wide. A wide box pushed left or right behaves like a row of part 1’s boxes. Pushed up or down, both its halves have to move, and each half can be pressing on a different box, so one push can lift a whole staircase or pyramid of boxes. If any box in it would hit a wall, nothing moves. A box scores by its left half, the [ (GPS counts to the box’s nearest edge). The larger example widened sums to 9021.

Part 2 on the larger example, widened. 700 moves is too many to watch one by one: after move 23 it jumps five moves at a time (75 a second), except for the biggest pushes.

Step 1: check first, then push

Widen the text, keep the list of lists, and treat the two directions apart. Sideways, [ and ] shift exactly like O did, so part 1’s row code works as it is. Up and down, two recursive functions: can_push asks whether a box can move, which means both halves have a free cell ahead or a box ahead that can itself move, and push moves the boxes ahead first, then this one:

WIDE = {"#": "##", "O": "[]", ".": "..", "@": "@."}


def widen(text: str) -> str:
    rows, moves = split_input(text)
    return "\n".join("".join(WIDE[ch] for ch in row) for row in rows) + "\n\n" + moves


def part2(text: str) -> int:
    rows, moves = split_input(widen(text))
    grid = [list(row) for row in rows]
    for r, row in enumerate(grid):
        for c, ch in enumerate(row):
            if ch == "@":
                robot = (r, c)

    def box_at(r: int, c: int) -> int:
        """The column of the box's left half, given either half."""
        return c if grid[r][c] == "[" else c - 1

    def can_push(r: int, c: int, dr: int) -> bool:
        for cc in (c, c + 1):
            ahead = grid[r + dr][cc]
            if ahead == "#":
                return False
            if ahead in "[]" and not can_push(r + dr, box_at(r + dr, cc), dr):
                return False
        return True

    def push(r: int, c: int, dr: int) -> None:
        for cc in (c, c + 1):
            if grid[r + dr][cc] in "[]":
                push(r + dr, box_at(r + dr, cc), dr)
        grid[r + dr][c], grid[r + dr][c + 1] = "[", "]"
        grid[r][c], grid[r][c + 1] = ".", "."

    for m in moves:
        dr, dc = MOVES[m]
        r, c = robot[0] + dr, robot[1] + dc
        ahead = grid[r][c]
        if ahead == "#":
            continue
        if ahead in "[]" and dr == 0:
            while grid[r][c] in "[]":
                c += dc
            if grid[r][c] == "#":
                continue
            while c != robot[1]:
                grid[r][c] = grid[r][c - dc]
                c -= dc
        elif ahead in "[]":
            if not can_push(r, box_at(r, c), dr):
                continue
            push(r, box_at(r, c), dr)
        grid[robot[0]][robot[1]] = "."
        robot = (robot[0] + dr, robot[1] + dc)
        grid[robot[0]][robot[1]] = "@"
    return sum(100 * r + c for r, row in enumerate(grid) for c, ch in enumerate(row) if ch == "[")

The split into two passes is the part that matters. A single function that checks and moves as it goes would happily move the left branch of a tree, then find a wall above the right branch, and leave the boxes torn apart.

push can reach the same box twice, when it rests on two boxes that both belong to the tree. The second time it finds . where the box was, because the first call already moved it, so it doesn’t move twice.

Step 2: one search for every direction

Step 1 has three cases: a free step, a sideways row, and a vertical tree. They’re the same thing seen differently. Starting from the robot, collect every cell that would have to move: look at the cell ahead of each collected cell; a wall means the move fails, a free cell ends that branch, and a box half gets collected along with its other half. Sideways, the other half is just the next cell along, which the search would reach anyway. That’s a breadth-first search, with collections.deque as the queue:

from collections import deque


def pushed(grid: dict[complex, str], robot: complex, d: complex) -> list[complex] | None:
    seen = [robot]
    todo = deque(seen)
    while todo:
        ahead = todo.popleft() + d
        ch = grid[ahead]
        if ch == "#":
            return None
        if ch == ".":
            continue
        partner = {"[": 1, "]": -1}.get(ch, 0)  # an O has no other half
        for p in (ahead, ahead + partner):
            if p not in seen:
                seen.append(p)
                todo.append(p)
    return seen

Moving them is then the same for every case: read what’s in each collected cell, clear them all, and write them all one step on. Because everything is read before anything is written, the order doesn’t matter, and nothing overwrites a box that hasn’t moved yet:

def run(text: str) -> dict[complex, str]:
    rows, moves = split_input(text)
    grid = {complex(c, r): ch for r, row in enumerate(rows) for c, ch in enumerate(row)}
    robot = next(p for p, ch in grid.items() if ch == "@")
    for m in moves:
        d = STEPS[m]
        cells = pushed(grid, robot, d)
        if cells is None:
            continue
        moving = {p: grid[p] for p in cells}
        for p in cells:
            grid[p] = "."
        for p, ch in moving.items():
            grid[p + d] = ch
        robot += d
    return grid


def gps(grid: dict[complex, str]) -> int:
    return int(sum(100 * p.imag + p.real for p, ch in grid.items() if ch in "O["))


def part2(text: str) -> int:
    return gps(run(widen(text)))

pushed never asks what kind of box it’s looking at: an O simply has no partner. So gps(run(text)) on the narrow map is a third answer to part 1, and the tests check it against step 1 of part 1 on 400 random maps, along with this version against step 1 of part 2.

It’s slower than step 1: about 15 ms against 5 ms on the same generated 50x50 map, since every move, even a free step, builds a deque, a list and a dict. (Those timings were taken while other jobs were loading the machine, so take them as rough.) That’s still nothing, and in exchange there’s one rule for all four directions and both parts, instead of three special cases.

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