You are given a 2D grid image[][] representing an image, where each cell contains a color value. You are also given a starting cell (sr, sc) and a new color newColor. Your task is to replace the color of the starting cell and all 4-directionally connected cells having the same original color with newColor.
Cells are connected only in four directions: Up, Down, Left, Right.
Return the updated image after performing the flood fill.
Input: image[][] = [ [1] ] sr = 0, sc = 0, newColor = 2
Output: [ [2] ]
Explanation: The single cell is recolored.
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] ]
Explanation: All connected cells with the same starting color are changed.
Input: image[][] = [ [0 0 0 0], [0 1 1 0], [0 1 1 0], [0 0 0 0] ] sr = 1, sc = 1, newColor = 3
Output: [ [0 0 0 0], [0 3 3 0], [0 3 3 0], [0 0 0 0] ]
Explanation: The connected region with the same color is filled with the new color.
Approach, complexity and clean code in every language. Sign in to unlock the editorial.
Your submissions, results and runtime history live here. Sign in to start your streak.
1 1 1 1 1 1 0 1 0 1 1 1 2
2 2 2 2 2 0 2 0 1
1 0 0 0 0 1 1 1 1 2
0 0 0 0 2 2
1 1 1 1 1 0 0 3
3 3 3 3