Java - Flood Fill Algorithm

Problem Statement

Given a 2D array representing an image, you need to flood fill the image starting from the given pixel and replace the original color with a new color in all 4-connected directions.

Example

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]

]

Java Code (DFS Approach)

import java.util.Arrays;

public class FloodFill {

    public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {

        int originalColor = image[sr][sc];

        if (originalColor == newColor)

            return image;

        dfs(image, sr, sc, originalColor, newColor);

        return image;

    }

    private void dfs(int[][] image, int r, int c, int originalColor, int newColor) {

        int rows = image.length;

        int cols = image[0].length;

        if (r < 0 || r >= rows || c < 0 || c >= cols)

            return;

        if (image[r][c] != originalColor)

            return;

        image[r][c] = newColor;

        dfs(image, r + 1, c, originalColor, newColor); // down

        dfs(image, r - 1, c, originalColor, newColor); // up

        dfs(image, r, c + 1, originalColor, newColor); // right

        dfs(image, r, c - 1, originalColor, newColor); // left

    }

    public static void main(String[] args) {

        FloodFill ff = new FloodFill();

        int[][] image = {

            {1, 1, 1},

            {1, 1, 0},

            {1, 0, 1}

        };

        int sr = 1, sc = 1, newColor = 2;

        int[][] result = ff.floodFill(image, sr, sc, newColor);

        System.out.println("Flood filled image:");

        for (int[] row : result) {

            System.out.println(Arrays.toString(row));

        }

    }

}