Problem Description
Given an m x n grid representing an image, where each cell represents a pixel's color, perform a flood fill starting from a given starting pixel (sr, sc). Change the starting pixel's color to a new given color, and then change all directly adjacent pixels (up, down, left, right) that have the same original color recursively. Stop when there are no more adjacent pixels with the original color.
Key Insights
- The flood fill operation can be executed using either DFS (Depth First Search) or BFS (Breadth First Search).
- A check is needed at the beginning to determine if the new color is the same as the original; if so, no changes are needed.
- The algorithm recursively or iteratively visits each pixel that is directly adjacent and matches the original color, then updates its color.
- The problem has a worst-case scenario where all pixels are the same color, leading to a full traversal of the grid.
Space and Time Complexity
Time Complexity: O(m * n), where m and n are the dimensions of the image grid, because in the worst-case all cells are visited. Space Complexity: O(m * n) in the worst-case due to the recursion stack (or BFS queue) if the entire image needs to be filled.
Solution
We use a DFS approach to perform the flood fill. The algorithm starts at the given starting pixel and uses recursion to fill connected pixels with the same original color. The following steps are key:
- Check if the starting pixel's color is already the target color; if so, return the image immediately.
- Define a recursive helper function that:
- Checks boundary conditions.
- Updates the current pixel's color.
- Recursively calls itself on the four adjacent directions (up, down, left, right).
- Return the modified image after the recursion completes.
Data structures used:
- Recursion call stack for the DFS implementation.
- Variables to store the image dimensions and original color.