Flood Fill - Problem
Flood Fill is a classic image processing algorithm that simulates the "paint bucket" tool found in graphics programs like MS Paint or Photoshop.
You're given an image represented as a 2D grid where each cell contains a pixel value (color). Starting from a specified pixel at position
The Process:
1. Start at pixel
2. Change this pixel to the new
3. Recursively do the same for all adjacent pixels (up, down, left, right) that have the same original color
4. Stop when no more connected pixels have the original color
Think of it like spilling paint on a connected area - it spreads to all touching pixels of the same color!
You're given an image represented as a 2D grid where each cell contains a pixel value (color). Starting from a specified pixel at position
(sr, sc), you need to "flood" all connected pixels of the same original color with a new color.The Process:
1. Start at pixel
image[sr][sc] and note its original color2. Change this pixel to the new
color3. Recursively do the same for all adjacent pixels (up, down, left, right) that have the same original color
4. Stop when no more connected pixels have the original color
Think of it like spilling paint on a connected area - it spreads to all touching pixels of the same color!
Input & Output
example_1.py โ Basic Flood Fill
$
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]]
๐ก Note:
Starting from center position (1,1) with original color 1, we flood fill with color 2. All connected pixels with value 1 get changed to 2, but the 0s act as boundaries and remain unchanged.
example_2.py โ Same Color Edge Case
$
Input:
image = [[0,0,0],[0,0,0]], sr = 0, sc = 0, color = 0
โบ
Output:
[[0,0,0],[0,0,0]]
๐ก Note:
The starting pixel already has the target color (0), so no changes are needed. The algorithm returns early to avoid infinite recursion.
example_3.py โ Single Pixel
$
Input:
image = [[1]], sr = 0, sc = 0, color = 3
โบ
Output:
[[3]]
๐ก Note:
Simple case with just one pixel. The pixel at (0,0) has value 1 and gets changed to 3.
Constraints
- m == image.length
- n == image[i].length
- 1 โค m, n โค 50
- 0 โค image[i][j], color < 216
- 0 โค sr < m
- 0 โค sc < n
Visualization
Tap to expand
Understanding the Visualization
1
Click Starting Pixel
User clicks on a blue pixel with red paint selected
2
Paint Spreads
Red paint spreads to all connected blue pixels
3
Boundaries Stop Spread
Yellow pixels act as boundaries - paint doesn't cross them
4
Filling Complete
All connected blue pixels are now red
Key Takeaway
๐ฏ Key Insight: Flood fill is like a smart paint bucket that only spreads to connected pixels of the same original color, making it perfect for region-based operations in graphics and image processing.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code