← Visualizers
Graphs · Flood fill on a grid LeetCode 200

Number of Islands / visualized

The graph is implicit — no adjacency list exists, neighbours are computed by (r±1, c) and (r, c±1). Scan every cell; each time you land on un-sunk land, that is one new island, so sink the whole component before the scan moves on.

Execution

idle
INVARIANT Mark & sink BEFORE recursing — in-place grid mutation prevents infinite loops and guarantees O(m·n) traversal.
Call Stack · Activation Records Top = Active · Bottom = Suspended Parents
Press Run to begin.
0 / 0
Speed

Java · running line

scan cursor current cell sinking now island finished water
INTERVIEW SCRIPT

How to Explain this Call Stack to an Interviewer

1. The Function Contract

"sink(r, c) is a flood-fill helper that mutates all connected land reachable from (r, c) into '0', effectively sinking the entire component."

2. The Pre-Order Invariant

"We mark grid[r][c] = '0' before recursing. If we waited, the first neighbor call (down) would immediately look up and call sink back on us, causing an infinite recursive loop!"

3. Frame Suspension & Unwinding

"When sink(0, 0) calls down to sink(1, 0), frame (0, 0) is suspended on the stack. It cannot advance to up, right, or left until the entire subtree under down returns."

4. Space Complexity Proof

"Time is O(m · n) since every cell is sunk once. Auxiliary space is bounded by the maximum call stack depth: O(m · n) in the worst case (a snake/spiral island filling the grid)."

O(m·n) time · O(m·n) worst-case recursion depth  ·  the cell is sunk before the four calls, not after — mark first, or the neighbours call straight back and the recursion never ends.