Flood Fill - Graph-Based Approach - Visualization

Visualization Player

Problem Statement

The Flood Fill problem is a classic image processing task. Given a 2D array image where each element represents the color of a pixel, a starting pixel coordinate (sr, sc), and a newColor, your task is to 'flood fill' the area connected to the starting pixel.

A pixel is considered 'connected' if it has the same color as the starting pixel and is connected 4-directionally (up, down, left, or right).

Replace all such connected pixels with newColor.

Examples

Image Start (sr, sc) newColor Output
[[1,1,1],[1,1,0],[1,0,1]]
[1, 1] 2 [[2,2,2],[2,2,0],[2,0,1]]
[[0,0,0],[0,1,1]]
[1, 1] 1 [[0,0,0],[0,1,1]]
[[1]]
[0, 0] 1 [[1]]
[[0,0],[0,0]]
[0, 0] 3 [[3,3],[3,3]]
[]
[0, 0] 1 []
[[1,1,2,2],[1,2,2,0],[1,1,0,0],[0,0,0,0]]
[0, 0] 9 [[9,9,2,2],[9,2,2,0],[9,9,0,0],[0,0,0,0]]
[[1,1,1,1],[1,0,0,1],[1,0,1,1],[1,1,1,1],[0,0,0,0]]
[1, 1] 5 [[1,1,1,1],[1,5,5,1],[1,5,1,1],[1,1,1,1],[0,0,0,0]]

Solution

Understanding the Problem

The Flood Fill algorithm is like using the paint bucket tool in an image editor. Given a 2D image (represented as a matrix), a starting pixel (row, col), and a new color, the goal is to change the color of the starting pixel and all its connected pixels (horizontally and vertically) that have the same original color.

We need to ensure we do not affect diagonally adjacent pixels, and we must avoid visiting out-of-bound positions or repeatedly coloring the same pixel.

Step-by-Step Solution with Example

Step 1: Understand the input and what must change

Suppose the input image is:

[
  [1, 1, 1],
  [1, 1, 0],
  [1, 0, 1]
]

The starting pixel is at position (1, 1), and the new color is 2. The original color at that pixel is 1. So we must flood all connected 1’s from that position and change them to 2.

Step 2: Decide the traversal approach

We can use either DFS (Depth-First Search) or BFS (Breadth-First Search). DFS can be implemented recursively, whereas BFS uses a queue. In either approach, we keep visiting neighbors in four directions: up, down, left, and right.

Step 3: Base condition check

If the color of the starting pixel is already the new color, we return the image as is. This avoids unnecessary work or infinite recursion.

Step 4: Start the traversal and coloring

Using DFS, we visit the starting pixel and recursively move to its neighbors that share the same color. We color each visited pixel with the new color before moving deeper.

Step 5: Watch the bounds and avoid reprocessing

For every neighbor, we ensure it's within image bounds and hasn’t already been colored. This prevents out-of-bounds errors or visiting the same node again and again.

Step 6: Final result after flood fill

After applying flood fill, the image becomes:

[
  [2, 2, 2],
  [2, 2, 0],
  [2, 0, 1]
]

All connected 1’s starting from position (1, 1) have been changed to 2.

Edge Cases

Edge Case 1: Starting pixel already has the new color

If the color at the start is already equal to the new color, no change should be done. This is to avoid infinite recursion or redundant operations.

Edge Case 2: Empty image

If the image is empty or has no pixels, the function should return it as is without error.

Edge Case 3: Boundary and corner starts

Starting from edges or corners should be handled correctly. This means extra care in checking if neighbors go out of bounds.

Edge Case 4: Large connected region

If a large portion of the image is connected and needs coloring, recursion could cause stack overflow. In such cases, BFS is preferred for safety.

Finally

The flood fill algorithm is a classic graph traversal problem. It can be solved using either DFS or BFS. The key to solving it efficiently lies in careful boundary checks, preventing re-coloring, and handling base conditions properly.

This problem builds a strong understanding of how grid-based traversal works, and introduces concepts like visited tracking, direction arrays, and recursion/iteration trade-offs.

Algorithm Steps

  1. Store the original color of the pixel at (sr, sc).
  2. If original color is same as newColor, return the image.
  3. Use BFS or DFS to explore from (sr, sc):
    1. Push starting pixel to the stack or queue.
    2. While the stack/queue is not empty:
      1. Pop a pixel and change its color to newColor.
      2. Push its 4-directional neighbors if they have the original color.
  4. Return the modified image.

Code

C
C++
Python
Java
JS
Go
Rust
Kotlin
Swift
TS
#include <stdio.h>

#define ROWS 3
#define COLS 3

void floodFill(int image[ROWS][COLS], int sr, int sc, int newColor, int originalColor) {
    if (sr < 0 || sc < 0 || sr >= ROWS || sc >= COLS || image[sr][sc] != originalColor || image[sr][sc] == newColor)
        return;
    image[sr][sc] = newColor;
    floodFill(image, sr + 1, sc, newColor, originalColor);
    floodFill(image, sr - 1, sc, newColor, originalColor);
    floodFill(image, sr, sc + 1, newColor, originalColor);
    floodFill(image, sr, sc - 1, newColor, originalColor);
}

int main() {
    int image[ROWS][COLS] = {{1,1,1},{1,1,0},{1,0,1}};
    int sr = 1, sc = 1, newColor = 2;
    int originalColor = image[sr][sc];
    floodFill(image, sr, sc, newColor, originalColor);
    for (int i = 0; i < ROWS; i++) {
        for (int j = 0; j < COLS; j++) {
            printf("%d ", image[i][j]);
        }
        printf("\n");
    }
    return 0;
}

Time Complexity

CaseTime ComplexityExplanation
Best CaseO(1)If the starting pixel's color is already the new color, the algorithm returns immediately without modifying the image.
Average CaseO(m × n)In most practical scenarios, a portion of the image is filled, and the algorithm visits those connected pixels once.
Worst CaseO(m × n)If the entire image consists of the same color, the algorithm may visit every pixel, making it linear in the size of the image.

Space Complexity

O(m × n)

Explanation: In the worst case, the stack or queue can hold all pixels of the image if they are all connected and need to be processed.


Comments

💬 Please keep your comment relevant and respectful. Avoid spamming, offensive language, or posting promotional/backlink content.
All comments are subject to moderation before being published.


Loading comments...