RecapDifficulty: Advanced1 min

Recap: Grid Traversal

A grid is a graph you never build: breadth-first for distances, a fill from every unreached cell for regions, many sources at once for nearest.

A grid is a graph whose vertices are its open cells and whose edges join each cell to the cells beside it, computed with four offsets and a bounds check rather than stored. The question decides the search and where it starts:

Grid questions and the search each needs
QuestionSearchStart fromMark whenCost
Fewest moves between two cellsBreadth-firstThe startAdded to the queueO(R · C)
How many regionsFlood fill, any orderEvery cell no fill has reachedAdded to the stackO(R · C)
Nearest of several sources, for every cellBreadth-firstEvery source at once, at distance 0Added to the queueO(R · C)
Regions that do not reach the edgeFlood fillEvery open edge cell first, then the restAdded to the stackO(R · C)

Marking a cell when it leaves the queue keeps the answer and lets the queue grow with the edges. Which neighbours count as joined, four or eight, changes how many regions a map holds, and a recursive fill on a large region can pass Python's recursion limit, so the fills here use a stack.