Implement flood fill using BFS and DFS
Problem
You are given a 2D grid image of size m × n, where each cell contains an integer color value. You are also given a starting cell (sr, sc) and an integer newColor.
Perform a flood fill starting from (sr, sc):
- Let
oldColor = image[sr][sc]. - Recolor
(sr, sc)and every cell 4-directionally connected (up, down, left, right) to(sr, sc)that has coloroldColortonewColor. - Return the modified
image.
If oldColor == newColor, the grid should remain unchanged.
Requirements
Write the solution in three ways:
- Using BFS .
- Using recursive DFS .
- Using iterative DFS (explicit stack; no recursion).
Inputs / Outputs
- Input:
image: int[m][n],sr: int,sc: int,newColor: int - Output: Modified
imageafter flood fill.
Constraints (typical)
1 ≤ m, n ≤ 500 ≤ sr < m,0 ≤ sc < n- Color values are non-negative integers.
Example
Given:
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]]
AI interview prep
Core dilemma
Efficiently traversing and modifying connected components in a grid while managing state and avoiding infinite loops, especially when implementing multiple traversal strategies.
3 tradeoffs and 3 stress tests locked
Interview prep
Unlock the interviewer X-Ray rubric, tradeoff matrix, stress tests, clarifying questions, and key concepts.
Implement flood fill using BFS and DFS
Problem
You are given a 2D grid image of size m × n, where each cell contains an integer color value. You are also given a starting cell (sr, sc) and an integer newColor.
Perform a flood fill starting from (sr, sc):
- Let
oldColor = image[sr][sc]. - Recolor
(sr, sc)and every cell 4-directionally connected (up, down, left, right) to(sr, sc)that has coloroldColortonewColor. - Return the modified
image.
If oldColor == newColor, the grid should remain unchanged.
Requirements
Write the solution in three ways:
- Using BFS .
- Using recursive DFS .
- Using iterative DFS (explicit stack; no recursion).
Inputs / Outputs
- Input:
image: int[m][n],sr: int,sc: int,newColor: int - Output: Modified
imageafter flood fill.
Constraints (typical)
1 ≤ m, n ≤ 500 ≤ sr < m,0 ≤ sc < n- Color values are non-negative integers.
Example
Given:
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]]