PrepStack · Markdown HTML

Grid flood fill

Traversal and connectivity · HTML

Formal shape

Vertices are cells (r,c), dirs generates edges, and a predicate controls admission. One flood reaches every eligible cell connected to the seed.

Recognition signals

False friends

SignalWhy it is different
Direction-restricted path countingWhen moves form a DAG and the goal is a count, use grid-dp.
Unequal-cost grid routingPlain flood fill does not optimize cost; use an ordered frontier.

Core invariant

Every cell in the frontier has passed bounds and predicate checks and is already marked; expansion only considers its eligible neighbors.

State, transition, and processing order

ItemDefinition
StateCell coordinate, visited representation or in-place mark, direction set, and optional region summaries such as area or boundary flags.
TransitionGenerate each neighboring coordinate, check bounds before access, check eligibility and visited, then mark and enqueue or push.
Frontier / orderA stack or queue; the order changes the trace but not the maximal region obtained.

Python skeleton

from collections import deque

def flood(grid, sr, sc, target, replacement):
    if not grid or not grid[0]:
        return 0
    rows, cols = len(grid), len(grid[0])
    if not (0 <= sr < rows and 0 <= sc < cols):
        return 0
    if target == replacement or grid[sr][sc] != target:
        return 0
    q = deque([(sr, sc)])
    grid[sr][sc] = replacement
    area = 0
    while q:
        r, c = q.popleft()
        area += 1
        for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
            nr, nc = r + dr, c + dc
            if 0 <= nr < rows and 0 <= nc < cols:
                if grid[nr][nc] == target:
                    grid[nr][nc] = replacement
                    q.append((nr, nc))
    return area

Correctness sketch

  1. Every admitted cell is eligible and adjacent to the reached region, so the search cannot escape it.
  2. Every target cell has a neighbor path to the seed; induction along that path proves discovery.
  3. Marking on enqueue gives at most one enqueue per cell and guarantees termination.

Complexity

TimeSpaceParameters
O(RC)O(RC)R and C are grid dimensions; actual work may equal one region's area, with full-grid worst case.

Edge cases

Error patterns

PatternWhy it fails / fix
Indexing before boundsPython negative indexes silently wrap to the far side.
In-place marking with the same valueIt removes the visited signal and permits repetition.
Wrong direction modelConfusing four- and eight-neighbor rules changes the components.

Selection and exclusion rules

RelationTemplateBoundary
adds an ordered frontierBest-first boundary flood / priority floodTraversal order starts determining effective boundary state.
grid specializationDFS components and reachabilityVertices are cells and directions generate neighbors.

Original micro-example

PartDetail
ResultThe area is 5 and the isolated x remains unchanged.
SetupFive x cells form one four-neighbor region; another x is separated by o cells.
TraceA seed inside the region recolors exactly the five reachable x cells to y.

Recall prompts

My notes