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.
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.
Flood Fill Cell State Transitions (Preventing Duplicate Enqueues)
Recoloring or marking visited at enqueue time (not pop time) prevents exponential duplicate insertions in diamond grids.
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.
Why Recursive DFS Crashes on Real Grids
- 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.
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.
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.
| Choice | What it buys | What 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 IDs | Tagging 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 Path | Dijkstra or A* accounts for terrain movement costs and heuristics. | Unweighted flood fill ignores edge weights completely. |
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.
Production-Safe Iterative BFS & Scanline Flood Fill
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))
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.
| Choice | What it buys | What 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. |
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).
Wavefront Propagation with Enqueue-Time Marking
Enforcing old==new guards and enqueue-time marking keeps time strictly O(R*C) with zero duplicate queue entries.
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: Make the trade-off yourself.
Why must BFS flood fill recolor or mark a neighbor cell as visited *before* pushing it onto the queue rather than when popping it?