Search⌘ K
AI Features

Solution: Flood Fill

Explore how to solve the flood fill problem with depth-first search and backtracking. This lesson helps you understand how to recursively fill connected pixels of the same color in a 2D grid, handle boundary checks, and optimize recursive calls. You will gain skills to apply this approach to similar combinatorial problems in coding interviews.

Statement

You are given a 2D grid of size m x n, where grid[i][j] represents the pixel value at position (i, j).

Additionally, you are given three integers:

  • sr: The row index of the starting pixel

  • sc: The column index of the starting pixel

  • target: The new color to apply

Your task is to perform a flood fill starting from the pixel at position (sr, sc). Below is the flood fill process:

  1. If the pixel at (sr, sc) already has the value target, return the original grid without any changes.

  2. Otherwise, start at the pixel grid[sr][sc] and change its color to the given color target. ...