Flood Fill Algorithm - Graph Based

Problem and examples

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.

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

Explore Flood Fill - Graph-Based Approach

Load an example or enter your own input. Use the player controls to follow each change.

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.

  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.

Implementation and efficiency

C implementation

#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;
}

C++ implementation

#include <iostream>
#include <vector>
using namespace std;

void floodFill(vector<vector<int>>& image, int sr, int sc, int newColor, int originalColor) {
    if (sr < 0 || sc < 0 || sr >= image.size() || sc >= image[0].size() || 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() {
    vector<vector<int>> image = {{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 (const auto& row : image) {
        for (int val : row) cout << val << " ";
        cout << endl;
    }
    return 0;
}

Python implementation

def flood_fill(image, sr, sc, new_color):
    original_color = image[sr][sc]
    if original_color == new_color:
        return image

    def dfs(r, c):
        if r < 0 or c < 0 or r >= len(image) or c >= len(image[0]) or image[r][c] != original_color:
            return
        image[r][c] = new_color
        dfs(r+1, c)
        dfs(r-1, c)
        dfs(r, c+1)
        dfs(r, c-1)

    dfs(sr, sc)
    return image

print(flood_fill([[1,1,1],[1,1,0],[1,0,1]], 1, 1, 2))

Java implementation

public class FloodFill {
    public static void main(String[] args) {
        int[][] image = {{1,1,1},{1,1,0},{1,0,1}};
        int sr = 1, sc = 1, newColor = 2;
        int originalColor = image[sr][sc];
        if (originalColor != newColor) {
            floodFill(image, sr, sc, newColor, originalColor);
        }
        for (int[] row : image) {
            for (int val : row) {
                System.out.print(val + " ");
            }
            System.out.println();
        }
    }

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

JavaScript implementation

function floodFill(image, sr, sc, newColor) {
  const originalColor = image[sr][sc];
  if (originalColor === newColor) return image;

  const rows = image.length;
  const cols = image[0].length;
  const queue = [[sr, sc]];

  const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]];
  image[sr][sc] = newColor;

  while (queue.length > 0) {
    const [r, c] = queue.shift();
    for (const [dr, dc] of directions) {
      const nr = r + dr, nc = c + dc;
      if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && image[nr][nc] === originalColor) {
        image[nr][nc] = newColor;
        queue.push([nr, nc]);
      }
    }
  }
  return image;
}

console.log(floodFill([[1,1,1],[1,1,0],[1,0,1]], 1, 1, 2));

Go implementation

package main

import (
    "fmt"
)

func floodFill(image [][]int, sr, sc, newColor int) [][]int {
    originalColor := image[sr][sc]
    if originalColor == newColor {
        return image
    }
    var dfs func(int, int)
    dfs = func(r, c int) {
        if r < 0 || c < 0 || r >= len(image) || c >= len(image[0]) || image[r][c] != originalColor {
            return
        }
        image[r][c] = newColor
        dfs(r+1, c)
        dfs(r-1, c)
        dfs(r, c+1)
        dfs(r, c-1)
    }
    dfs(sr, sc)
    return image
}

func main() {
    image := [][]int{{1,1,1},{1,1,0},{1,0,1}}
    result := floodFill(image, 1, 1, 2)
    for _, row := range result {
        fmt.Println(row)
    }
}

Rust implementation

fn flood_fill(image: &mut Vec<Vec<i32>>, sr: usize, sc: usize, new_color: i32, original_color: i32) {
    if sr >= image.len() || sc >= image[0].len() || image[sr][sc] != original_color || image[sr][sc] == new_color {
        return;
    }
    image[sr][sc] = new_color;
    if sr > 0 { flood_fill(image, sr - 1, sc, new_color, original_color); }
    if sc > 0 { flood_fill(image, sr, sc - 1, new_color, original_color); }
    flood_fill(image, sr + 1, sc, new_color, original_color);
    flood_fill(image, sr, sc + 1, new_color, original_color);
}

fn main() {
    let mut image = vec![vec![1,1,1], vec![1,1,0], vec![1,0,1]];
    let sr = 1;
    let sc = 1;
    let new_color = 2;
    let original_color = image[sr][sc];
    flood_fill(&mut image, sr, sc, new_color, original_color);
    for row in image {
        println!("{:?}", row);
    }
}

Kotlin implementation

fun main() {
    val image = arrayOf(intArrayOf(1,1,1), intArrayOf(1,1,0), intArrayOf(1,0,1))
    val sr = 1
    val sc = 1
    val newColor = 2
    val originalColor = image[sr][sc]
    if (originalColor != newColor) {
        floodFill(image, sr, sc, newColor, originalColor)
    }
    for (row in image) println(row.joinToString(" "))
}

fun floodFill(image: Array<IntArray>, r: Int, c: Int, newColor: Int, originalColor: Int) {
    if (r !in image.indices || c !in image[0].indices || image[r][c] != originalColor) return
    image[r][c] = newColor
    floodFill(image, r+1, c, newColor, originalColor)
    floodFill(image, r-1, c, newColor, originalColor)
    floodFill(image, r, c+1, newColor, originalColor)
    floodFill(image, r, c-1, newColor, originalColor)
}

Swift implementation

func floodFill(_ image: inout [[Int]], _ sr: Int, _ sc: Int, _ newColor: Int, _ originalColor: Int) {
    if sr < 0 || sr >= image.count || sc < 0 || sc >= image[0].count || 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)
}

var image = [[1,1,1],[1,1,0],[1,0,1]]
let sr = 1, sc = 1, newColor = 2
let originalColor = image[sr][sc]
floodFill(&image, sr, sc, newColor, originalColor)
for row in image {
    print(row)
}

TypeScript implementation

function floodFill(image: number[][], sr: number, sc: number, newColor: number): number[][] {
  const originalColor = image[sr][sc];
  if (originalColor === newColor) return image;
  const rows = image.length;
  const cols = image[0].length;

  const dfs = (r: number, c: number) => {
    if (r < 0 || r >= rows || c < 0 || c >= cols || image[r][c] !== originalColor) return;
    image[r][c] = newColor;
    dfs(r + 1, c);
    dfs(r - 1, c);
    dfs(r, c + 1);
    dfs(r, c - 1);
  };

  dfs(sr, sc);
  return image;
}

console.log(floodFill([[1,1,1],[1,1,0],[1,0,1]], 1, 1, 2));

Time complexity

CaseTimeExplanation
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)

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.