← blog

Twenty-Five Days · day 12 · both parts

Day 12: Garden Groups

the puzzle ↗ #aoc-2024#python

Part 1 is a flood fill, the grid puzzle everyone has written before. Part 2 asks for something that sounds fiddly, the number of straight sides of an irregular shape with holes in it, and the interesting part is that you can count something else that is easier.

The puzzle, in my words

A map of letters, one per garden plot. Plots with the same letter that touch up, down, left or right form a region, and the same letter can make several regions, some inside others. Each region needs a fence, priced at its area (the number of plots) times its perimeter (the number of plot edges that face something else: another letter, or the edge of the map).

The small example is a 4x4 map:

AAAA
BBCD
BBCC
EEEC

Region A is a row of four plots with a perimeter of 10, so it costs 40. With B (4 times 8), C (4 times 10), D (1 times 4) and E (3 times 8), the total is 140. The larger example, a 10x10 map with eleven regions, totals 1930.

Part 1: area times perimeter

Part 1 on the larger example. Pink: waiting in the queue; gold: done. Right: each region’s area x perimeter.

Step 1: the first version

Walk the map in reading order. Each plot that isn’t in a region yet starts a new one: flood-fill it with a queue, a breadth-first search. Every time a plot comes off the queue, look at its four neighbours. A neighbour with the same letter belongs to the region (queue it if it’s new); anything else, including the edge of the map, means a piece of fence.

from collections import deque

DIRS = [(-1, 0), (0, 1), (1, 0), (0, -1)]


def part1(text: str) -> int:
    grid = text.split()
    rows, cols = len(grid), len(grid[0])
    seen = set()
    total = 0
    for r in range(rows):
        for c in range(cols):
            if (r, c) in seen:
                continue
            plant = grid[r][c]
            seen.add((r, c))
            queue = deque([(r, c)])
            area = 0
            perimeter = 0
            while queue:
                y, x = queue.popleft()
                area += 1
                for dy, dx in DIRS:
                    ny, nx = y + dy, x + dx
                    if 0 <= ny < rows and 0 <= nx < cols and grid[ny][nx] == plant:
                        if (ny, nx) not in seen:
                            seen.add((ny, nx))
                            queue.append((ny, nx))
                    else:
                        perimeter += 1
            total += area * perimeter
    return total

A plot is marked as seen when it is queued, not when it comes off the queue, so nothing is queued twice. The fill is a loop rather than recursion on purpose: 140 by 140 is the size reported for real maps, and one region that covered it would be 19,600 plots deep for a recursive fill, and Python’s default recursion limit is 1,000. The tests run a single 140x140 region through every step.

Step 2: regions as sets, positions as complex numbers

Two changes. First, a position becomes a complex number, column + row × 1j, and the map a dict from position to letter. A neighbour is p + d for d in 1, 1j, -1, -1j, and grid.get(p + d) is None off the map, so the bounds check goes. Second, finding the regions becomes its own function that returns each one as a set of positions. The fill order no longer matters, so a plain list used as a stack will do:

def parse(text: str) -> dict[complex, str]:
    return {complex(x, y): ch for y, line in enumerate(text.split()) for x, ch in enumerate(line)}


def regions(grid: dict[complex, str]) -> list[set[complex]]:
    seen: set[complex] = set()
    out = []
    for start, plant in grid.items():
        if start in seen:
            continue
        region, stack = {start}, [start]
        while stack:
            p = stack.pop()
            for d in (1, 1j, -1, -1j):
                q = p + d
                if q not in region and grid.get(q) == plant:
                    region.add(q)
                    stack.append(q)
        seen |= region
        out.append(region)
    return out

With a region in hand as a set, a piece of fence is any side whose neighbour isn’t in the set, and the perimeter is one sum (a True counts as 1):

def part1(text: str) -> int:
    total = 0
    for region in regions(parse(text)):
        perimeter = sum(p + d not in region for p in region for d in (1, 1j, -1, -1j))
        total += len(region) * perimeter
    return total

This is shorter, not faster. On a generated 140x140 map with about 540 regions, step 1 takes about 10 ms and step 2 about 16 ms. Finding the regions alone takes 11 ms, already more than all of step 1, and the perimeter is then a second walk over every region’s set. (Keying the same regions by (row, column) tuples instead of complex numbers saves only about a millisecond.) The point is the split. Part 2 needs the same regions and only changes how a region is priced.

Part 2: area times sides

Now the price is the area times the number of sides, where a side is a straight stretch of fence, however long. Region A in the small example is a rectangle, so 4 sides; C is a zigzag with 8. The small example comes to 80 and the larger one to 1206.

Holes count. Two extra examples check the tricky cases: an E shape with two bars cut into it (236), and an A region with two B squares inside that touch only at one corner (368). The fence doesn’t run across that point, so A has 4 sides outside and 8 inside.

Part 2 on the same map. Each dark dot is a corner, and a region has as many sides as corners.

Step 1: merge the pieces of fence into runs

Collect every piece of fence of a region as a pair: the plot, and the direction it faces. Then group the pieces that lie on the same line and face the same way, sort them along the line, and count the runs: each gap starts a new side.

from itertools import pairwise


def fences(region: set[complex]) -> set[tuple[complex, complex]]:
    return {(p, d) for p in region for d in (1, 1j, -1, -1j) if p + d not in region}


def part2(text: str) -> int:
    total = 0
    for region in regions(parse(text)):
        lines: dict[tuple[complex, float], list[float]] = {}
        for p, d in fences(region):
            if d.real == 0:  # fence on the top or bottom: a horizontal line
                key, along = (d, p.imag), p.real
            else:  # fence on the left or right: a vertical line
                key, along = (d, p.real), p.imag
            lines.setdefault(key, []).append(along)
        sides = 0
        for positions in lines.values():
            positions.sort()
            sides += 1
            for a, b in pairwise(positions):
                if b != a + 1:  # a gap: a new run, so a new side
                    sides += 1
        total += len(region) * sides
    return total

The direction in the key is what the 368 example is there to catch. A’s fence above the lower B square and A’s fence below the upper one sit on the same grid line and meet end to end at the point where the two squares touch. They face opposite ways, though, so they are two sides. Group by the line alone and they merge into one: A gets 10 sides instead of 12, and the example comes out at 312 instead of 368.

Step 2: count each side at its end

There’s no need to build the runs to count them. Multiplying a direction by 1j turns it by 90 degrees, so p + d * 1j is the next plot along the same fence line. A piece of fence is the last one of its side exactly when that plot has no fence facing the same way, and every side has exactly one last piece:

def part2(text: str) -> int:
    total = 0
    for region in regions(parse(text)):
        pieces = fences(region)
        sides = sum((p + d * 1j, d) not in pieces for p, d in pieces)
        total += len(region) * sides
    return total

No grouping and no sorting: one set and one sum.

Step 3: count corners

Step 2 counted one end of each side. Count both ends and you get the corners: each side has two ends, each end is a corner, and each corner is where exactly two sides meet. So a region has exactly as many corners as sides, on the outside and around every hole.

A corner can be spotted from a single plot. Take two of its neighbours at right angles, p + d and p + d * 1j:

  • both outside the region: the fence turns round this plot, an outside corner;
  • both inside, but the plot diagonally between them outside: the fence turns in, an inside corner.
def part2(text: str) -> int:
    total = 0
    for region in regions(parse(text)):
        corners = 0
        for p in region:
            for d in (1, 1j, -1, -1j):
                a, b = p + d in region, p + d * 1j in region
                corners += (not a and not b) or (a and b and p + d + d * 1j not in region)
        total += len(region) * corners
    return total

The pinch point in the 368 example works out on its own. The two A plots that meet there each see an outside corner on that point, so it counts twice, and it should: four of A’s sides end there.

This isn’t the fastest of the three. On the same generated 140x140 map the steps take about 22, 19 and 27 ms; the corner check looks up to three plots up in the region for each of the four directions of every plot. What it gains is that it needs nothing but the region: no fence pieces, no grouping, just a look at the 3x3 neighbourhood of each plot. The direct version from step 1 keeps it honest: the tests run all three steps on 400 random small maps of two or three letters, where holes and regions meeting at a corner turn up all the time, and on a generated full-size map, and check that they agree.

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