Skip to main content
← CONCEPTS / ALGORITHMS & DATA STRUCTURES
An end-to-end domain learning journey

Flood Fill &
Grid Component Traversal.

A graph traversal (BFS, iterative DFS, or scanline span-fill) that discovers and relabels all vertices reachable from a seed node under an adjacency and predicate rule.
Start the journey7 sections· Last modified Oct 23, 2026
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

When concurrent writes contend on shared state, never use recursive DFS on large grids—an explicit queue or scanline span-fill prevents stack overflows while cutting frontier memory by up to 10x.

TL;DR30-second simplified summary
▾

Core Mechanics: Flood fill treats a 2D grid or raster image as an implicit graph where each cell (r, c) connects to its 4-directional (orthogonal) or 8-directional neighbors sharing a matching predicate (e.g., grid[nr][nc] == seedColor).

Visual & Structural Flow: Depicts Flood Fill Cell State Transitions (Preventing Duplicate Enqueues) (TARGET (oldColor) -> MARKED / QUEUED -> EXPANDED); Wavefront Propagation with Enqueue-Time Marking (FloodFill Guard -> BFS Deque -> Grid[r][c]).

Trade-Offs & Production: Choose the traversal strategy based on memory bounds, cache locality, and whether minimum hop distance matters. In multiplayer game servers and image editors, flood fill must also guard against color-tolerance drift (comparing candidates against the immutable seedColor, never the.

Failure Modes & Application: Explore broader graph traversal, cycle detection, and disjoint-set algorithms.

Before you begin · Building blocksAlready know these? Jump to Stage 01 ↓
Core Algorithm Patterns: Two Pointers, Fast & Slow, Sliding Window & DP
Four foundational algorithmic paradigms—Two Pointers, Fast & Slow Pointers, Sliding Window, and Dynamic Programming—that turn brute-force O(n^2) or O(2^n) searches into optimal O(n) or polynomial-time solutions.
Full walkthrough · 7 stages
01
STAGE 01 · WHAT IT ISL4 · FUNDAMENTALS

What is Flood Fill.

Why this matters: The mechanism: understand how Flood Fill works from first principles.

Flood fill treats a 2D grid or raster image as an implicit graph where each cell (r, c) connects to its 4-directional (orthogonal) or 8-directional neighbors sharing a matching predicate (e.g., grid[nr][nc] == seedColor).

Starting from a seed (sr, sc), traversal visits every connected cell in the component and relabels it to newColor. Two invariants prevent catastrophic bugs: (1) guard if oldColor == newColor: return immediately, and (2) mark cells visited before pushing them onto the queue.

Cell Lifecycle

Flood Fill Cell State Transitions (Preventing Duplicate Enqueues)

Recolor BEFORE pushPop & scan 4-adjNeighbor skips (already…TARGET (oldColor)Matches seed predicateMARKED / QUEUEDRecolored at enqueueEXPANDED4-neighbors checked

Recoloring or marking visited at enqueue time (not pop time) prevents exponential duplicate insertions in diamond grids.

02
STAGE 02 · WHY WE NEED ITL4 · FUNDAMENTALS

Why Recursive DFS Crashes on Real Grids.

Why this matters: The problem: see what breaks without Why Recursive DFS Crashes on Real Grids under real concurrency or scale.

Each recursive stack frame consumes ~32–64 bytes.

A serpentine path across a 1024 x 1024 grid (1 million depth) requires 32–64 MB of call stack—blowing past Linux's default 8 MB ulimit -s stack limit and crashing with a segfault.

Lifecycle & Failure Recovery

Why Recursive DFS Crashes on Real Grids

admitsucceedbudget exceededInitializedProcessingInvariant MetDegraded Fallback
Engineering Decision Framework
Problem
How to implement Flood Fill & Grid Component Traversal without hitting unbounded tail latency, state divergence, or operational fragility.
Naive Solution
Use a single unpartitioned path with unbounded retries and synchronous global coordination.
Why It Fails
Global coordination serializes throughput under load, while unbounded retries amplify transient stalls into full outages.
Alternatives
Compare synchronous strict-consistency paths against bounded asynchronous replication, local caching, or partitioned ownership.
Engineering Decision
When concurrent writes contend on shared state, never use recursive DFS on large grids—an explicit queue or scanline span-fill prevents stack overflows while cutting frontier memory by up to 10x.
Trade-Offs
Gains predictable p99 latency and fault isolation in exchange for explicit bounding, observability, and slightly higher implementation complexity.
Decision Exercise · Make the Call

When Flood Fill & Grid Component Traversal experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?

Enqueue-Time Marking

Set grid[nr][nc] = newColor the instant a neighbor passes bounds and color checks, before appending to the queue.

Scanline Span-Fill

Process entire horizontal runs [x_left, x_right] per queue entry, shrinking frontier queue size by up to 10x on open 4K canvases.

03
STAGE 03 · WHERE IT IS USEDL5 · APPLIED DESIGN

Where Flood Fill Fits (and When to Use Union-Find or Dijkstra).

Why this matters: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.

Think of Where Flood Fill Fits (and When to Use Union-Find or Dijkstra) as the intuition layer for Flood Fill & Grid Component Traversal: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.

Use flood fill for single-seed region discovery; switch to Union-Find for repeated static reachability or Dijkstra for weighted paths.

ChoiceWhat it buysWhat it costs
Good Candidate: 4K Raster Bucket Fill (OpenCV)Scanline span-fill processes contiguous horizontal pixels sequentially, maximizing CPU prefetcher hits.Span boundary checks require careful off-by-one testing.
Good Candidate: Pre-Computed Navmesh Island IDsTagging walkable tiles with `islandId` (`uint16`) at map load turns runtime reachability into an O(1) comparison.Dynamic terrain edits require localized re-flooding.
Avoid: Shortest Weighted PathDijkstra or A* accounts for terrain movement costs and heuristics.Unweighted flood fill ignores edge weights completely.
04
STAGE 04 · HOW IT IS MANAGEDL5 · APPLIED DESIGN

Production-Safe Iterative BFS & Scanline Flood Fill.

Why this matters: Operational control: configure bounds, failure handling, and safe production defaults.

Think of Production-Safe Iterative BFS & Scanline Flood Fill as the intuition layer for Flood Fill & Grid Component Traversal: Operational control: configure bounds, failure handling, and safe production defaults.

Use an explicit collections.deque (or pre-allocated ring buffer) with an upfront old_color == new_color guard and enqueue-time mutation.

Request & State Flow

Production-Safe Iterative BFS & Scanline Flood Fill

CallerService EntryCore ProcessorState Store1. Submit bounded request2. Apply domain invariant3. Persist or read state4. Return verified response
from collections import deque

def flood_fill_bfs(grid: list[list[int]], sr: int, sc: int, new_color: int) -> None:
    rows, cols = len(grid), len(grid[0])
    old_color = grid[sr][sc]
    if old_color == new_color:
        return  # Guard against no-op infinite loop

    grid[sr][sc] = new_color
    q = deque([(sr, sc)])
    while q:
        r, c = q.popleft()
        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 and grid[nr][nc] == old_color:
                grid[nr][nc] = new_color  # Mark BEFORE enqueue
                q.append((nr, nc))
05
STAGE 05 · ALTERNATIVESL6 · SCALE & TRADE-OFFS

Alternatives: Iterative BFS vs. Iterative DFS vs. Scanline Span-Fill.

Why this matters: The trade-off: compare competing approaches across latency, consistency, and operational cost.

Think of Alternatives: Iterative BFS vs. Iterative DFS vs. Scanline Span-Fill as the intuition layer for Flood Fill & Grid Component Traversal: The trade-off: compare competing approaches across latency, consistency, and operational cost.

Choose the traversal strategy based on memory bounds, cache locality, and whether minimum hop distance matters.

ChoiceWhat it buysWhat it costs
Iterative BFS (`deque`)Expands in concentric waves (minimum hop distance) and bounds frontier to `O(min(R, C))` on simple shapes.Enqueues every individual pixel on open 4K regions.
Scanline Span-Fill (Queue-Linear)10x smaller queue and sequential horizontal memory reads friendly to CPU cache.More complex span-merging logic than 12-line BFS.
Two-Pass Union-Find (Disjoint Set)Labels all connected components in a static binary mask in two cache-linear raster scans.Processes the entire image even if you only need one small clicked region.
06
STAGE 06 · PRODUCTION ARCHITECTUREL7 · STAFF / PRINCIPAL

Production Pattern: Pre-Tagged Island IDs & Fixed-Range Tolerance.

Why this matters: Production architecture: see how the components compose end to end under real load.

Think of Production Pattern: Pre-Tagged Island IDs & Fixed-Range Tolerance as the intuition layer for Flood Fill & Grid Component Traversal: Production architecture: see how the components compose end to end under real load.

In multiplayer game servers and image editors, flood fill must also guard against color-tolerance drift (comparing candidates against the immutable seedColor, never the neighbor's color) and immutable grid snapshots (using a separate visited bitset when concurrent readers inspect the map).

Traversal Trace

Wavefront Propagation with Enqueue-Time Marking

FloodFill GuardBFS DequeGrid[r][c]1. old == new? -> early return2. Mark seed & push (sr, sc)3. Pop (r,c), mark valid neighbors4. Already marked? -> skip push

Enforcing old==new guards and enqueue-time marking keeps time strictly O(R*C) with zero duplicate queue entries.

07
STAGE 07 · PROBLEMS SOLVED & FURTHER DEEP DIVEL7 · STAFF / PRINCIPAL

Related Graph & Component Traversal Concepts.

Why this matters: Applied problems: connect these internals to concrete system design and debugging scenarios.

Think of Related Graph & Component Traversal Concepts as the intuition layer for Flood Fill & Grid Component Traversal: Applied problems: connect these internals to concrete system design and debugging scenarios.

Explore broader graph traversal, cycle detection, and disjoint-set algorithms.

Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

Why must BFS flood fill recolor or mark a neighbor cell as visited *before* pushing it onto the queue rather than when popping it?

Recommended Learning Flow