← blog

Twelve Days · day 4 · both parts

Day 4: Printing Department

the puzzle ↗ #aoc-2025#python

A grid day. Part 1 is counting neighbours, and the steps are about how to hold a grid in Python. Part 2 repeats part 1 until nothing changes, and the interesting part is that the obvious way rescans the whole grid every round when only a handful of cells changed.

The puzzle, in my words

A grid shows rolls of paper (@) and empty floor (.). A forklift can reach a roll if fewer than four of the eight cells around it, diagonals included, hold rolls (the puzzle calls those rolls accessible). Count the rolls it can reach.

The example is a 10x10 grid with 71 rolls:

..@@.@@@@.
@@@.@.@.@@
@@@@@.@.@@
@.@@@@..@.
@@.@@@@.@@
.@@@@@@@.@
.@.@.@.@@@
@.@@@.@@@@
.@@@@@@@@.
@.@.@@@.@.

Thirteen of them have three neighbours or fewer: five along the top row, the rest on the edges, plus one inside at row 3.

Part 1: rolls with fewer than four neighbours

Part 1 on the example. Each roll gets its neighbour count; red means under 4. Right: how many rolls have each count.

Step 1: the first version

Loop over every cell; for each roll, look at the eight cells around it and skip the ones that fall off the grid.

def part1(text: str) -> int:
    grid = text.split()
    rows, cols = len(grid), len(grid[0]) if grid else 0
    reachable = 0
    for r in range(rows):
        for c in range(cols):
            if grid[r][c] != "@":
                continue
            neighbours = 0
            for dr in (-1, 0, 1):
                for dc in (-1, 0, 1):
                    if dr == 0 and dc == 0:
                        continue
                    nr, nc = r + dr, c + dc
                    if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == "@":
                        neighbours += 1
            if neighbours < 4:
                reachable += 1
    return reachable

Nothing wrong with it, and it is the fastest of the three part 1 steps here. Most of the lines are bookkeeping, though, and the bounds check is the line that is easy to get wrong.

Step 2: a set of rolls, as complex numbers

Only the rolls matter, so keep just their positions in a set. A complex number makes a handy 2D point: the real part is the column, the imaginary part the row, and moving to a neighbour is adding one of eight fixed steps. Asking “is there a roll here?” is a set lookup, and a cell off the grid is simply not in the set, so the bounds check disappears:

DIRS = [complex(dx, dy) for dy in (-1, 0, 1) for dx in (-1, 0, 1) if dx or dy]


def rolls_in(text: str) -> set[complex]:
    return {
        complex(x, y)
        for y, line in enumerate(text.split())
        for x, ch in enumerate(line)
        if ch == "@"
    }


def part1(text: str) -> int:
    rolls = rolls_in(text)
    return sum(sum(p + d in rolls for d in DIRS) < 4 for p in rolls)

Both sums count booleans: True adds 1. The inner one counts a roll’s neighbours, the outer one counts the rolls whose total is under 4.

Step 3: let every roll count itself into its neighbours

Turn the question round. Instead of each roll looking at its eight neighbours, each roll adds 1 to the count of every cell around it. A Counter does the bookkeeping, and a roll with no rolls around it is never added, which is fine: a Counter returns 0 for a key it doesn’t have.

from collections import Counter


def neighbour_counts(rolls: set[complex]) -> Counter:
    return Counter(p + d for p in rolls for d in DIRS)


def part1(text: str) -> int:
    rolls = rolls_in(text)
    counts = neighbour_counts(rolls)
    return sum(counts[p] < 4 for p in rolls)

The work is the same (eight steps per roll) and on a generated 139x139 grid all three steps take about 10 ms. The point of this one is that the counts now sit in a table, and part 2 can update that table instead of recomputing it.

Part 2: peel until nothing moves

Now the reachable rolls are taken away. That leaves their neighbours with fewer rolls around them, so some of those become reachable, and so on. Keep going until no roll is reachable and count everything taken. On the example that runs for nine rounds, taking 13, 12, 7, 5, 2, 1, 1, 1 and 1 rolls: 43 in all, with 28 left.

Part 2 on the example, round by round. Pink numbers: the round each roll was taken in. Right: how many each round took.

Step 1: in rounds, as the rule says

Find every reachable roll against the grid as it stands, take them all away together, repeat:

def part2(text: str) -> int:
    rolls = rolls_in(text)
    removed = 0
    while True:
        reachable = {p for p in rolls if sum(p + d in rolls for d in DIRS) < 4}
        if not reachable:
            return removed
        rolls -= reachable
        removed += len(reachable)

Each round checks every roll that is left, so the cost is rounds times rolls. The example needs nine rounds; a random grid at puzzle size needs more. On a generated 139x139 grid at the example’s density (about 71% rolls), it took 43 rounds (the same number as the example’s answer, by coincidence) and between 300 and 450 ms across runs.

Step 2: only recheck what a removal touches

Taking a roll away changes exactly eight counts: its neighbours’. Nothing else on the grid can have become reachable. So keep the counts from part 1’s step 3, put the reachable rolls in a queue, and each time one is taken, lower the counts around it. A neighbour whose count drops to exactly 3 has just become reachable, so it joins the queue. Exactly 3, not “under 4”, so that nothing is queued twice:

from collections import deque


def part2(text: str) -> int:
    rolls = rolls_in(text)
    counts = neighbour_counts(rolls)
    queue = deque(p for p in rolls if counts[p] < 4)
    removed = 0
    while queue:
        p = queue.popleft()
        rolls.remove(p)
        removed += 1
        for d in DIRS:
            q = p + d
            counts[q] -= 1
            if q in rolls and counts[q] == 3:
                queue.append(q)
    return removed

Lowering the count of an empty cell is harmless (a Counter lets it go negative), so the loop doesn’t need to check before it subtracts.

This takes the rolls one at a time, not in rounds, so why does it give the same answer? Because a removal can only lower counts. A roll that is reachable stays reachable until it is taken, so taking rolls in a different order can’t save one that would otherwise go. Every order ends with the same rolls left: the largest set in which each roll has at least four neighbours inside the set. That also means the queue could be a plain list used as a stack. With the deque the rolls happen to come off round by round: all of round 1, then all of round 2, and so on, because a roll only joins the queue when a roll from the round before it is taken. The tests check that as well.

Each roll is queued at most once and costs eight updates, so the time is proportional to the number of rolls, whatever the number of rounds. On the same generated grid this takes about 17 ms instead of 300 or more. The tests run both versions on 300 random grids of different sizes and densities and check they agree.

All of this was checked on the puzzle’s example and on generated grids, not on a puzzle input of my own. The 139x139 size comes from a public solution and couldn’t be checked here.