Taro Logo

Flood Fill

#3 Most AskedEasy
0 views
Topics:
ArraysRecursionGraphs

You are given an image represented by an m x n grid of integers image, where image[i][j] represents the pixel value of the image. You are also given three integers sr, sc, and color. Your task is to perform a flood fill on the image starting from the pixel image[sr][sc].

To perform a flood fill:

  1. Begin with the starting pixel and change its color to color.
  2. Perform the same process for each pixel that is directly adjacent (pixels that share a side with the original pixel, either horizontally or vertically) and shares the same color as the starting pixel.
  3. Keep repeating this process by checking neighboring pixels of the updated pixels and modifying their color if it matches the original color of the starting pixel.
  4. The process stops when there are no more adjacent pixels of the original color to update.

Return the modified image after performing the flood fill.

Example 1:

Input: 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]]

Explanation:

From the center of the image with position (sr, sc) = (1, 1) (i.e., the red pixel), all pixels connected by a path of the same color as the starting pixel (i.e., the blue pixels) are colored with the new color.

Note the bottom corner is not colored 2, because it is not horizontally or vertically connected to the starting pixel.

Example 2:

Input: image = [[0,0,0],[0,0,0]], sr = 0, sc = 0, color = 0

Output: [[0,0,0],[0,0,0]]

Explanation:

The starting pixel is already colored with 0, which is the same as the target color. Therefore, no changes are made to the image.

Constraints:

  • m == image.length
  • n == image[i].length
  • 1 <= m, n <= 50
  • 0 <= image[i][j], color < 216
  • 0 <= sr < m
  • 0 <= sc < n

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What are the maximum dimensions of the 2D grid, and can the grid be non-square (rectangular) or empty?
  2. What is the range of possible color values in the grid, and can the new color be identical to the starting pixel's original color?
  3. Should the flood fill operation modify the input 2D grid in-place, or should I allocate and return a new grid?
  4. How should invalid starting coordinates (e.g., out of bounds or negative indices) be handled if they are passed as input?
  5. Are diagonal connections considered valid for the flood fill, or are we strictly restricted to 4-directional (horizontal and vertical) adjacency?

Brute Force Solution

Approach

Imagine looking at a grid of colored tiles and wanting to repaint a connected patch of tiles with a new color. The brute force approach involves blindly checking every single tile in the entire grid to see if it is connected to your starting point and shares the original color.

Here's how the algorithm would work step-by-step:

  1. Start by looking at the specific tile where your pointing device begins.
  2. Check if this starting tile has the original color you want to change.
  3. If it does not match, you stop immediately because there is nothing to change.
  4. If it does match, mentally repaint this tile with the new target color.
  5. From this tile, look at all of its immediate neighbors located directly above, below, to the left, and to the right.
  6. For each of those neighbors, repeat the exact same process of checking its color and repainting it if it matches.
  7. Continue this process of checking and repainting for every newly reached neighbor, branching out in all directions until no more matching connected tiles can be found anywhere in the grid.

Code Implementation

def flood_fill(image_grid, start_row, start_column, new_color):    original_color = image_grid[start_row][start_column]    # Stop immediately if the starting color already matches the target to prevent infinite recursion    if original_color == new_color:        return image_grid    total_rows = len(image_grid)    total_columns = len(image_grid[0])    def recursive_fill(current_row, current_column):        # Boundary check ensures we do not attempt to inspect indices lying outside the grid dimensions        if current_row < 0 or current_row >= total_rows or current_column < 0 or current_column >= total_columns:            return        # Halt traversal on this path if the current tile does not match the original color we are replacing        if image_grid[current_row][current_column] != original_color:            return        image_grid[current_row][current_column] = new_color        recursive_fill(current_row - 1, current_column)        recursive_fill(current_row + 1, current_column)        recursive_fill(current_row, current_column - 1)        recursive_fill(current_row, current_column + 1)    recursive_fill(start_row, start_column)    return image_grid

Big(O) Analysis

Time Complexity
O(R * C) – Let R be the number of rows and C be the number of columns in the grid, making the total number of pixels equal to n = R * C. In the worst-case scenario, every single pixel in the grid shares the starting color and must be visited and repainted by our recursive algorithm. Since each pixel is visited at most a constant number of times and its four immediate neighbors are checked, the total number of operations scales directly with the total number of tiles. This results in approximately R * C operations, which simplifies to the Big O time complexity of O(R * C) or O(n).
Space Complexity
O(N) – The space complexity is driven by the recursion stack frames when branching out to immediate neighbors in all directions, as well as tracking visited tiles to prevent infinite loops. Let N be the total number of pixels in the grid in the worst-case scenario where every tile matches the starting color and must be repainted. The depth of the recursive calls can grow to occupy space proportional to N. Therefore, the auxiliary space complexity simplifies to Big O of N.

Optimal Solution

Approach

The optimal strategy is like spreading paint on a canvas, where you start at your chosen spot and let the new color flow outward to all touching neighbors of the same original color. By tackling connected areas step by step and keeping track of where you have already been, you change the entire region efficiently without getting stuck in loops.

Here's how the algorithm would work step-by-step:

  1. Check the starting spot to see what color it currently is.
  2. If the starting spot is already the target color you want to paint, you do not need to do anything and can stop right there.
  3. Otherwise, remember the original color of the starting spot so you know which neighboring areas are allowed to change.
  4. Change the color of your current spot to the new target color.
  5. Look at all the touching neighbors directly above, below, to the left, and to the right of your current spot.
  6. For any neighbor that matches the original color you remembered, treat that neighbor as your new spot and repeat the coloring process.
  7. Keep flowing outward to new touching neighbors until every connected piece of the original color has been completely updated to the new color.

Code Implementation

class Solution:
    def floodFill(self, image_grid: list[list[int]], start_row: int, start_column: int, target_color: int) -> list[list[int]]:
        original_color = image_grid[start_row][start_column]
        
        # Prevent infinite loops and redundant work if the color is already target.
        if original_color == target_color:
            return image_grid

        total_rows = len(image_grid)
        total_columns = len(image_grid[0])

        def recursive_paint(current_row: int, current_column: int):
            # Stop recursion if we drift outside grid boundaries or hit a different color.
            if current_row < 0 or current_row >= total_rows or current_column < 0 or current_column >= total_columns:
                return
            
            if image_grid[current_row][current_column] != original_color:
                return

            # Update current cell to target color before visiting its neighbors.
            image_grid[current_row][current_column] = target_color

            recursive_paint(current_row - 1, current_column)
            recursive_paint(current_row + 1, current_column)
            recursive_paint(current_row, current_column - 1)
            recursive_paint(current_row, current_column + 1)

        recursive_paint(start_row, start_column)
        
        # Return the modified grid containing the completed flood fill.
        return image_grid

Big(O) Analysis

Time Complexity
O(N) – In the worst-case scenario where every pixel in the grid matches the original starting color, the algorithm visits and recolors every single pixel. Let N be the total number of pixels in the grid (rows multiplied by columns). Since the recursive process checks up to four neighbors for each pixel and marks visited cells to prevent infinite loops, each pixel is processed at most a constant number of times. This directly scales the total operations proportionally to N, which simplifies to Big O of N.
Space Complexity
O(N) – The space complexity is driven by the recursion stack frames used when flowing outward to touching neighbors, where N represents the total number of pixels in the grid. In the worst-case scenario, such as a grid entirely filled with the same color, the recursive depth can grow to visit all N pixels. Therefore, the maximum memory consumed by the call stack scales linearly with the size of the grid. No additional data structures are required beyond the implicit system stack storing these recursive activation records.

Edge Cases

Starting pixel already has the target color
How to Handle:
To prevent infinite recursion, immediately check if the original color equals the new color and return the grid unchanged.
Grid is empty, null, or has dimensions of zero
How to Handle:
Validate the input dimensions at the start and return the grid immediately if it is empty.
Starting coordinates are out of the grid bounds
How to Handle:
Check boundary conditions before accessing the grid to prevent index out of bounds exceptions.
Minimum-sized 1x1 grid
How to Handle:
The algorithm will update the single pixel's color and safely return the grid without triggering out of bounds recursive calls.
Extremely large grid exceeding recursion stack limits
How to Handle:
Use an iterative approach with a queue or stack instead of pure recursion to avoid stack overflow errors on massive inputs.
Grid where all pixels already match the starting color
How to Handle:
The algorithm will traverse and update every single cell in the grid efficiently within time complexity limits.
Pixels contain negative numbers, zeros, or extreme color values
How to Handle:
Since the algorithm only checks for equality against the original color, arbitrary integer values are handled transparently.
0/5 completed