Given a 2D grid img[][] representing an image, where each element img[i][j] is an integer that denotes the color of a pixel. Also there is a coordinates (sr, sc) representing the starting pixel (row sr and column sc) and an integer newColor, which represents the new color to apply. We need to perform a flood fill on the image starting from (sr, sc). It means we must change the color of the starting pixel and all other pixels that are connected to it (directly or indirectly) and have the same original color as the starting pixel. Two pixels are considered connected if they are adjacent horizontally or vertically (not diagonally).
Output: [[2, 2, 2, 0], [0, 2, 2, 2], [1, 0, 2,2]] Explanation: Starting from pixel (1, 2) with value 1, flood fill updates all connected pixels (up, down, left, right) with value 1 to 2. The pixel at (2, 0) remains unchanged because it has no adjacent 1 connected to the starting pixel.
Input: sr = 0, sc = 1, newColor = 0, img[][] = [[0, 1, 0], [0, 1, 0]] Output: [[0, 0, 0], [0, 0, 0]] Explanation: Starting from pixel (0, 1) which has value 1, flood fill updates all connected pixels (up, down, left, right) with value 1 to 0.
[Approach 1] Using Depth-First Search - O(m * n) Time and O(m * n) Auxiliary Space
The idea is to use Depth-First Search (DFS) because DFS explores all connected cells deeply before backtracking. we need to change the color of the starting pixel and all other pixels that are connected to it having the same original color. So, we can think of it like this:
We start from the given pixel (sr, sc) and store its color as oldColor. Then, we begin a DFS from that cell. For each cell, we check all its four neighboring cells, If the neighbor is inside the grid and has the same color as oldColor, then that means this pixel should also be filled with the new color. We update it with newColor and recursively call DFS for that neighbor to continue spreading the new color further. If a neighbor has a different color or is outside the grid, we simply return without going deeper. Once all connected cells are visited, weโll have our final filled image.
Output
2 2 2 0
0 2 2 2
1 0 2 2
[Approach 2] Using Breadth-First Search - O(m * n) Time and O(m * n) Space
The idea is the same as DFS, but instead of using recursion, we use Breadth-First Search (BFS) because it avoids recursion overhead.
In BFS, we use a queue and traverse level by level. We start from the given pixel, change its color to the new one, and push it into the queue. Then, for each pixel we pop, we check all four adjacent cellsโif any neighbor has the same old color, we update it with the new color and add it to the queue. This continues until all connected pixels are updated.