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 (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 color
2. Change this pixel to the new color
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!

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
Flood Fill Algorithm - DFS Approach INPUT Original Image Grid (3x3) 1 1 1 1 1 START 0 1 0 1 Parameters: sr = 1 (start row) sc = 1 (start col) newColor = 2 originalColor = 1 = 1 = 0 ALGORITHM STEPS 1 Start at (1,1) Check if color differs from newColor 2 Change Color Set image[1][1] = 2 (mark as visited) 3 DFS to Neighbors Recurse: up, down, left, right 4 Base Cases Stop if: out of bounds, or color != original DFS Order: (1,1)-->(0,1)-->(0,0) -->(0,2)-->(1,0)-->(2,0) Connected 1s filled FINAL RESULT Modified Image Grid 2 2 2 2 2 0 2 0 1 Output: [[2,2,2], [2,2,0], [2,0,1]] OK - 5 connected cells filled with new color = 2 (filled) = 1 (not connected) Key Insight: DFS naturally handles flood fill by exploring all connected pixels of the same color before backtracking. The 0s act as barriers, preventing the fill from reaching the isolated 1 at position (2,2). Time: O(m*n), Space: O(m*n) TutorialsPoint - Flood Fill | DFS Approach
Asked in
Google 42 Amazon 38 Microsoft 35 Meta 28 Adobe 25
52.8K Views
Medium-High Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen