Flood Fill
Explore how to implement the flood fill algorithm using backtracking techniques to change connected pixel colors in a 2D grid. Understand the problem constraints and apply depth-first search to solve this common coding interview pattern effectively.
We'll cover the following...
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 pixelsc: The column index of the starting pixeltarget: 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:
If the pixel at
(sr, sc)already has the valuetarget, return the original grid without any changes.Otherwise, start at the pixel
grid[sr][sc]and change its color to the given colortarget.Perform the same operation for all 4-directionally adjacent pixels (up, down, left, right) with the same original color as the starting pixel.
Continue this process by examining the neighboring pixels of each updated pixel and changing their color if they match the original color of the starting pixel.
The process continues until no more ...