Back to problems Solve on LeetCode → See #200 Number of Islands →

Flood Fill

Stack DFS / Recursive — Single Flood from (sr, sc)

LeetCode 733 • Easy • Graphs

Input: image = [[1,1,1],[1,1,0],[1,0,1]], sr=1, sc=1, newColor=2  →  Output: [[2,2,2],[2,2,0],[2,0,1]]
From (sr,sc), replace all same-color cells with newColor. 4-direction flood.

TimeO(R×C)visit each cell once
SpaceO(R×C)stack worst case
Stack: 0 Filled: 0
Processing
In Stack
Filled
Original
Stack
empty
Filled
{ }
Ready
Press Play to watch stack-based DFS flood fill from (1,1), or Step to advance one operation at a time.
Replace all same-color cells with newColor. Stack DFS = iterative version of recursion.