Introduction
Flood Fill is one of the most popular Matrix DFS and BFS interview problems.
You are given:
image[][]sr
sc
color
Goal:
Change the color of all connected cells having the same original color.Movement:
Up
Down
LeftRight
Example
image =[[1,1,1],[1,1,0],[1,0,1]]sr = 1
sc = 1
color = 2
Output:
[[2,2,2],[2,2,0],[2,0,1]]Key Observation
Starting from:
(sr, sc) Visit every connected cell having:
Original Color Replace it with:
New ColorAlgorithm
1. Store original color.
2. Start DFS/BFS.
3. Visit valid neighbors.
4. Replace color.5. Continue traversal.
Dry Run
Input:
[[1,1,1],[1,1,0],[1,0,1]] Start:
(1,1) Replace:
All connected 1s with 2Answer:
[[2,2,2],[2,2,0],[2,0,1]]Approach : DFS
Explanation
For every cell:
- Check boundaries.
- Check original color.
- Replace color.
- Visit 4 directions.