Browse Curriculum
Depth-First Search
Easy

Flood Fill

Implement the 'Paint Bucket' tool found in image editors.
Examples
Input:image = [[1,1,1],[1,1,0],[1,0,1]], sr = 1, sc = 1, newColor = 2
Output:[[2,2,2],[2,2,0],[2,0,1]]
Explain:

Start at pixel (1,1). All connected '1's become '2'.

Problem Understanding

You are given an m x n integer grid image representing a bitmap image. You are also given a starting pixel (sr, sc) and a newColor.

You need to perform a Flood Fill: change the color of the starting pixel and all 4-directionally connected pixels of the same color to newColor.

Think of the 'Bucket Fill' tool in Paint.

Algorithm Strategy

This is a standard DFS traversal on a grid.

  1. Check Color: If image[sr][sc] == newColor, we don't need to do anything (avoid infinite loop).
  2. Store Old Color: We only move to neighbors that match oldColor.
  3. DFS Function: dfs(r, c)
    • Check Bounds: If out of bounds, return.
    • Check Match: If image[r][c] != oldColor, return.
    • Paint: Update image[r][c] = newColor.
    • Recurse: Call dfs for Up, Down, Left, Right.

Visualization

Step 1 / 1

Visualization data missing

Initializing...

1x

Watch the color spread outward from the center.

Stop Guessing, Start Mastering.

Build the FAANG intuition. Master this pattern with optimized implementations, visual dry runs, and our curated collection of high-yield problems.