Skip to content
Veltoryx Technologies
FreeProblem 106● EasyLeetCode #733 ↗4 min readUpdated 30 October 2026

Flood Fill

Perform flood fill on a 2D image using 4-directional DFS recursion.

01The problem

An image is represented by an m x n integer grid image where image[i][j] represents the pixel value of the image.

You are also given three integers sr, sc, and color. You should perform a flood fill on the image starting from the pixel image[sr][sc].

To perform a flood fill, consider the starting pixel, plus any pixels connected 4-directionally to the starting pixel of the same color as the starting pixel, plus any pixels connected 4-directionally to those pixels (also with the same color), and so on. Replace the color of all of the aforementioned pixels with color.

Return the modified image after performing the flood fill.

InputOutputWhy
image = [[1,1,1],[1,1,0],[1,0,1]], sr = 1, sc = 1, color = 2[[2,2,2],[2,2,0],[2,0,1]]All 1s connected to (1,1) become 2. Bottom-right 1 is disconnected.

Constraints

  • m == image.length
  • n == image[i].length
  • 1 <= m, n <= 50
  • 0 <= image[i][j], color < 2^16
  • 0 <= sr < m
  • 0 <= sc < n

02How to spot it

  • "Flood fill" / "Bucket fill tool": Classic connected component traversal starting from a single coordinate.
  • Guarded DFS: Check boundary limits and verify image[r][c] == oldColor before recursing.

03Pseudocode

text
old = image[sr][sc]
if old == color: return image
fill(r, c):
  if outside or img[r][c] != old: return
  image[r][c] = color
  fill the 4 neighbours

04Watch it work

Visualizer · step through the algorithmimage = [[1,1,1],[1,1,0],[1,0,1]], sr = 1, sc = 1, color = 2

image grid

111
110
101

old color

1

new color

2

Start flood fill from (1, 1) with target color 2. Old color is 1.

Pseudocode

  1. old = image[sr][sc]
  2. if old == color: return image
  3. fill(r, c):
  4. if outside or img[r][c] != old: return
  5. image[r][c] = color
  6. fill the 4 neighbours

Variables

sr
1
sc
1
color
2
old
1
step 1 / 5

05Step-by-step dry run

We trace on image = [[1,1,1],[1,1,0],[1,0,1]], sr = 1, sc = 1, color = 2:

StepPixel (r, c)Initial valActionGrid state
1(1, 1)1Start pixel: paint 2, explore neighbors[[1,1,1],[1,2,0],[1,0,1]]
2(0, 1)1Paint 2, explore up, left, right[[1,2,1],[1,2,0],[1,0,1]]
3(0, 0)1Paint 2, explore left/down[[2,2,1],[1,2,0],[1,0,1]]
4(0, 2)1Paint 2[[2,2,2],[1,2,0],[1,0,1]]
5(1, 0) & (2, 0)1Paint 2 down left column[[2,2,2],[2,2,0],[2,0,1]]
6(2, 2)1Not 4-directionally connected to any filled 1: left untouched![[2,2,2],[2,2,0],[2,0,1]]

06Java solution

java
import java.util.*;

public class Solution {
    public static int[][] floodFill(int[][] image, int sr, int sc, int color) {
        int oldColor = image[sr][sc];
        if (oldColor != color) {
            fill(image, sr, sc, oldColor, color);
        }
        return image;
    }

    private static void fill(int[][] img, int r, int c, int oldColor, int newColor) {
        if (r < 0 || r >= img.length || c < 0 || c >= img[0].length || img[r][c] != oldColor) {
            return;
        }
        img[r][c] = newColor;
        fill(img, r + 1, c, oldColor, newColor);
        fill(img, r - 1, c, oldColor, newColor);
        fill(img, r, c + 1, oldColor, newColor);
        fill(img, r, c - 1, oldColor, newColor);
    }

    public static void main(String[] args) {
        int[][] image = {
            {1, 1, 1},
            {1, 1, 0},
            {1, 0, 1}
        };
        int[][] res = floodFill(image, 1, 1, 2);
        System.out.println(Arrays.deepToString(res));
    }
}
Expected output
[[2, 2, 2], [2, 2, 0], [2, 0, 1]]

07Why it works

Changing the pixel color directly in image[r][c] = newColor serves as the visited marker. Any cell already changed will fail the condition img[r][c] != oldColor, naturally terminating infinite recursion.

08Time and space

  • Time complexity: O(m * n) in the worst case where every pixel in the grid shares the initial color and is painted.
  • Space complexity: O(m * n) recursion stack space in the worst case (e.g. a snake-shaped winding component).

09Edge cases

  • oldColor == color: Critical check! If the start pixel already has the target color, recursing would loop infinitely. The guard if (oldColor != color) prevents this.
  • 1x1 grid: Changes the single cell and returns immediately.

10Common mistakes

  • Forgetting the oldColor == color guard: Leads to immediate StackOverflowError when the new color matches the current color.

11Other approaches

  • BFS with Queue: Push (sr, sc) to a queue, dequeue and check 4 neighbors.

12In the interview

  • Opening line: "I will use 4-directional DFS. The base case checks grid boundaries and whether the cell matches oldColor. To prevent infinite cycles, I verify oldColor != color at the outset."

13Quiz

What happens if image[sr][sc] == color and we don't guard against it?

  • (Recommended) The program enters infinite recursion and crashes with a StackOverflowError
  • It correctly returns the image unchanged
  • It turns the entire image to 0
  • It throws an ArrayIndexOutOfBoundsException

Answer: The program enters infinite recursion and crashes with a StackOverflowError.

14Solve it yourself

Open LeetCode #733 and submit the DFS solution.