Understanding the Flood Fill Problem
The flood fill algorithm works similarly to how a paint bucket tool works in image editing software. Given a 2D array (image), a starting pixel, and a new color, it replaces the color of the starting pixel and all adjacent pixels (up/down/left/right) that share the same original color with the new color.
Case 1: Base Case - No Fill Needed
If the starting pixel's color is already equal to the new color, no changes are needed. This is an important check to avoid infinite loops during recursion or unnecessary processing in iterative traversal.
Case 2: Small Connected Region
When the starting pixel is part of a small isolated region with a unique color, the algorithm will only modify that small region. Both DFS and BFS work efficiently here, visiting a handful of connected nodes.
Case 3: Large Connected Area
If the connected region is large (e.g., a full row or the entire image), the algorithm will traverse every pixel in that region. The graph-based approach (DFS or BFS) will visit each of those connected pixels and change their color.
Case 4: Edge and Corner Pixels
When starting from the edge or corner of the image, the algorithm behaves the same, but care must be taken to avoid accessing pixels outside the image boundary. The 4-directional neighbors must be validated to stay within bounds.
DFS vs BFS: Which One?
Both DFS (using a stack or recursion) and BFS (using a queue) are valid. DFS may use less space for shallow fills, but recursion could lead to stack overflow for very large regions. BFS uses a queue and is safer for large datasets but might consume more memory.