Skip to main content

Flood Fill - Solution & Explanation

EasyArrayDepth-First SearchBreadth-First SearchMatrix29 min readAsked at: Amazon, Microsoft, Apple +9
Practice this problem

Problem Statement

You are given an image represented by an m x n grid of integers image, where image[i][j] represents the pixel value of the image. You are also given three integers sr, sc, and color. Your task is to perform a flood fill on the image starting from the pixel image[sr][sc].

To perform a flood fill:

  1. Begin with the starting pixel and change its color to color.
  2. Perform the same process for each pixel that is directly adjacent (pixels that share a side with the original pixel, either horizontally or vertically) and shares the same color as the starting pixel.
  3. Keep repeating this process by checking neighboring pixels of the updated pixels and modifying their color if it matches the original color of the starting pixel.
  4. The process stops when there are no more adjacent pixels of the original color to update.

Return the modified image after performing the flood fill.

 

Example 1:

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]]

Explanation:

From the center of the image with position (sr, sc) = (1, 1) (i.e., the red pixel), all pixels connected by a path of the same color as the starting pixel (i.e., the blue pixels) are colored with the new color.

Note the bottom corner is not colored 2, because it is not horizontally or vertically connected to the starting pixel.

Example 2:

Input: image = [[0,0,0],[0,0,0]], sr = 0, sc = 0, color = 0

Output: [[0,0,0],[0,0,0]]

Explanation:

The starting pixel is already colored with 0, which is the same as the target color. Therefore, no changes are made to the image.

 

Constraints:

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

Approach Overview

Problem Overview: You are given a 2D image where each cell represents a pixel color. Starting from a specific pixel (sr, sc), change its color and all 4-directionally connected pixels with the same original color to a new color. The task is essentially traversing a connected component in a grid.

Approach 1: Recursive Depth-First Search (DFS) (Time: O(m*n), Space: O(m*n))

This approach treats the grid as a graph and performs a recursive DFS from the starting cell. First store the original color at (sr, sc). If the new color is the same as the original, return immediately to avoid infinite recursion. Otherwise, recursively explore the four directions (up, down, left, right). Whenever a neighboring cell has the same original color, update it and continue the DFS. Each cell is visited at most once, giving O(m*n) time for an image of size m x n. The recursion stack can grow up to the size of the connected region, resulting in O(m*n) space in the worst case. This method is simple and maps naturally to problems involving Depth-First Search on a matrix.

Approach 2: Iterative Breadth-First Search (BFS) (Time: O(m*n), Space: O(m*n))

The BFS approach performs the same region traversal but uses a queue instead of recursion. Start by pushing the initial pixel into a queue and recolor it. While the queue is not empty, pop a cell and examine its four neighbors. If a neighbor lies within bounds and has the original color, recolor it and push it into the queue. BFS expands level by level across the connected component, ensuring every valid pixel is processed exactly once. Time complexity remains O(m*n) because each pixel is enqueued and processed at most once. Space complexity is also O(m*n) due to the queue in the worst case when the entire grid belongs to the same region. This approach is useful when recursion depth might be large and iterative control is preferred, especially in problems involving Breadth-First Search over an array-backed grid.

Recommended for interviews: The recursive DFS solution is the most common answer because it is concise and clearly demonstrates understanding of grid traversal. Interviewers typically expect you to recognize the problem as a connected component search. Mentioning both DFS and BFS shows strong fundamentals: DFS demonstrates recursion and graph traversal intuition, while BFS shows awareness of iterative alternatives and stack depth limitations.

Approach 1: Recursive Depth-First Search (DFS) Approach

This approach uses recursion to explore all connected pixels that need to be updated. Starting from the initial pixel, you recursively attempt to update all four possible directions (up, down, left, right) whenever the neighboring pixel has the same original color.

The recursion ensures that all connected and valid pixels are eventually updated. Make sure to handle the base case where the function stops if the pixel is out of bounds or if it doesn't need updating (either because it's already updated or has a different color).

In this Python solution, we define a recursive function dfs which updates the color of a pixel and then recursively calls itself for each adjacent pixel. The function checks boundary conditions and whether the pixel is of the original color before updating it.

Code

Python

C

C++

Java

C#

JavaScript

Complexity

Time Complexity: O(m * n) because in the worst case, all of the pixels will be connected and thus changed.
Space Complexity: O(m * n) due to the recursion call stack.

Try this approach in the editor →

Approach 2: Iterative Breadth-First Search (BFS) Approach

This approach employs an iterative breadth-first search (BFS) using a queue. Starting from the initial pixel, we enqueue it and begin the BFS process, updating connected pixels of the same original color to the new color.

For each pixel, check its adjacent pixels and enqueue them if they are valid and of the original color. This continues until the queue is empty, ensuring all pixels are updated appropriately.

This Python solution uses a queue to implement the BFS process, iterating over each pixel and its adjacent pixels. The queue ensures all connected pixels are enqueued and processed correctly.

Code

Python

C

C++

Java

C#

JavaScript

Complexity

Time Complexity: O(m * n), where m and n are the dimensions of the image (same as DFS).
Space Complexity: O(m * n), as we may store all pixels in the queue in the worst-case scenario.

Try this approach in the editor →

Approach 3: DFS

We denote the initial pixel's color as oc. If oc is not equal to the target color color, we start a depth-first search from (sr, sc) to change the color of all eligible pixels to the target color.

The time complexity is O(m times n), and the space complexity is O(m times n). Here, m and n are the number of rows and columns of the 2D array image, respectively.

Code

Python

Java

C++

Go

TypeScript

Rust

Try this approach in the editor →

Approach 4: BFS

We first check if the initial pixel's color is equal to the target color. If it is, we return the original image directly. Otherwise, we can use the breadth-first search method, starting from (sr, sc), to change the color of all eligible pixels to the target color.

Specifically, we define a queue q and add the initial pixel (sr, sc) to the queue. Then, we continuously take pixels (i, j) from the queue, change their color to the target color, and add the pixels in the four directions (up, down, left, right) that have the same original color as the initial pixel to the queue. When the queue is empty, we have completed the flood fill.

The time complexity is O(m times n), and the space complexity is O(m times n). Here, m and n are the number of rows and columns of the 2D array image, respectively.

Code

Python

Java

C++

Go

TypeScript

Rust

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Recursive Depth-First Search (DFS) Approach

Time Complexity: O(m * n) because in the worst case, all of the pixels will be connected and thus changed.
Space Complexity: O(m * n) due to the recursion call stack.

Iterative Breadth-First Search (BFS) Approach

Time Complexity: O(m * n), where m and n are the dimensions of the image (same as DFS).
Space Complexity: O(m * n), as we may store all pixels in the queue in the worst-case scenario.

DFS—
BFS—

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Recursive DFSO(m*n)O(m*n)Best for concise implementation and typical interview solutions involving recursive grid traversal
Iterative BFSO(m*n)O(m*n)Useful when avoiding recursion depth limits or when iterative queue-based traversal is preferred

Video Solution

G-9. Flood Fill Algorithm | C++ | Java • take U forward • 465,975 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Flood Fill easy or hard?
Flood Fill is classified as an Easy problem on LeetCode with a relatively high acceptance rate. The challenge mainly involves recognizing it as a grid traversal problem and correctly handling boundaries and repeated visits.
How to solve Flood Fill in O(n)?
Treat the grid as a graph and traverse the connected component using DFS or BFS. Store the original color, then explore four directions from the starting cell and recolor matching neighbors. Each pixel is visited once, resulting in O(m*n) time for a grid with m rows and n columns.
What is the best approach for Flood Fill?
Depth-First Search (DFS) is the most common approach. Starting from the source pixel, recursively visit neighboring cells that share the same original color and update them to the new color. Each cell is processed once, giving O(m*n) time complexity for an m x n image.
What data structure is used in Flood Fill?
Flood Fill uses either the call stack for recursive DFS or a queue for iterative BFS. The image itself is typically represented as a 2D array or matrix, and traversal checks the four directional neighbors of each cell.
What is the time complexity of Flood Fill?
Flood Fill runs in O(m*n) time because every pixel in the grid can be visited at most once during the traversal. Both DFS and BFS implementations have the same complexity since they explore the connected component of the starting pixel.
Flood Fill Python or Java solution approach?
In Python or Java, the solution typically implements recursive DFS that checks boundary conditions and color matches before recursing to neighbors. An alternative BFS version uses a queue to iteratively process pixels level by level.
Is Flood Fill asked at Google, Amazon, or Meta?
Flood Fill and similar grid traversal problems appear in interviews at major companies including Amazon, Google, and Meta. The problem tests understanding of graph traversal, recursion, and matrix boundary handling.

Ready to solve this problem?

Practice Flood Fill with our built-in code editor and test cases.

Practice on FleetCode