Skip to content
advent of code 2023

day 10

pipe maze

approach

the grid is first split into connected groups of pipes with an iterative dfs. the shape of S is then inferred from two neighbouring pipes that point back at it and belong to the same group, and S is replaced by that pipe. part 1 is a bfs along the loop from S; the number of layers is the furthest distance.

part 2 gets the loop as an ordered path and walks along it. for every step it looks at the cells to one side (turning the step direction counter-clockwise, or clockwise in a second pass) and flood-fills any unvisited cell it finds, with the loop cells already marked as visited. one side is the inside of the loop and the other is the outside, so the program prints both counts; a comment says the smaller one is the answer for this input.

the trick

walk the loop and flood-fill everything on one hand; that side is either all inside or all outside.

python
def solve(grid, path, f):
    visited = set(path)
    res = 0
    counted = set()
    for (r1, c1), (r2, c2) in zip(path, path[1:]):
        dr, dc = f(r2 - r1, c2 - c1)
        for nr, nc in [(r1+dr, c1+dc), (r2+dr, c2+dc)]:
            if in_bounds(grid, nr, nc) and (nr, nc) not in visited:
                res += floodfill(grid, nr, nc, visited)
                #print(f"res is {res}")
                #print(format(grid, set(path), visited), end = "\n\n")
    return res