Flood Fill

Paint a pixel and every pixel of the same color joined to it, like a paint bucket tool.

An image is stored as a grid of integers, image, where image[r][c] is the color of the pixel in row r, column c. Paint the pixel at row sr, column sc with a new color, color. Then paint every pixel that has the start pixel's original color and can be reached from it by steps up, down, left or right over pixels of that same color. Return the image after the 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: the 1 at row 2, column 2 touches the painted pixels only at a corner, so it stays 1.
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 new color is the same as the old one, so nothing changes.
Solution

The Idea

Most drawing programs have a paint bucket tool. You click inside a shape, and the new color pours into it, stopping wherever the color changes. This problem asks us to write that tool, on an image where each number stands for one color.

The picture shows Example 1 before and after the fill, with rows and columns (col for short) numbered from 0.

Example 1 before and after the fill. Starting at row 1, col 1, six pixels of color 1 are painted 2, in the order row 1 col 1, row 0 col 1, row 0 col 2, row 0 col 0, row 1 col 0, row 2 col 0. The pixel at row 2, col 2 meets them only at a corner and stays 1.

On the left, the start pixel at row 1, col 1 has an orange outline, and its color is 1. The grey pixels hold 0 and act as walls. On the right, six pixels now hold 2 and are drawn in teal. The pixel at row 2, col 2 is a 1 as well, yet it stays 1, because it meets the teal pixels only at a corner.

So which pixels does the fill reach? Their color alone does not tell us, since row 2, col 2 has the right color and is still left alone. What counts is whether a chain of steps up, down, left or right, all over pixels of color 1, leads to it from the start.

That suggests a way to find the chain: paint a pixel, look at its four neighbors, and repeat from every neighbor that still has color 1. The small numbers in the teal pixels give the paint order. From pixel 1, the start pixel, the fill first looks down, but row 2, col 1 is grey. Up is row 0, col 1, which becomes pixel 2, and the fill carries on from there before pixel 1 tries any other direction.

From pixel 2, the fill goes right to row 0, col 2, pixel 3. That pixel has nowhere new to go, so the fill backs up to pixel 2 and tries left: row 0, col 0 becomes pixel 4. From there it runs down to row 1, col 0 (pixel 5) and row 2, col 0 (pixel 6).

Following one path as deep as it goes, then backing up to try the next direction, is called depth-first search, or DFS. In this example, pixel 1 does not look to its right, at the grey row 1, col 2, until all six pixels are painted.

Solution Approach

Four decisions turn that search into code: moving to the neighbors, where a step stops, not painting a pixel twice, and a new color that equals the old one.

Moving to the neighbors

How does the code follow one path deep and then come back? A helper method, fill, paints one pixel and then calls itself once for each neighbor: down, up, right and left. When the call for pixel 3 at row 0, col 2 runs out of directions, it returns, and the call for pixel 2 goes on with its next direction.

Because fill calls itself, it is a recursive method. Each unfinished call, such as the one for pixel 2 while pixel 3 is being handled, waits on Java's call stack, the list of calls that have started but not yet returned, until the calls it made have returned.

Where a step stops

When should a call give up at once? When its pixel lies outside the image, such as the pixel above row 0, col 1, or when the pixel's color differs from the start pixel's original color, such as the grey row 2, col 1. Both checks sit at the top of fill, so the four calls inside it need no checks of their own.

Remembering painted pixels

Does the search come back to pixels it has already painted? It does: pixel 2 at row 0, col 1 looks down at pixel 1. A separate grid of "visited" flags would work, but painting already does that job. Pixel 1 now holds 2, not the original 1, so the color check sends that call straight back.

When the new color is the old one

What happens in Example 2, which paints 0 over 0? Painting then changes nothing, so a painted pixel still looks unpainted, and two neighbors keep calling each other with no end. The image is already correct in that case, so the code compares the two colors before it calls fill, and skips the fill when they are equal.

Java Solution

The method floodFill works in these steps:

  1. First, read the start pixel's color into original with image[sr][sc].
  2. If original equals color, there is nothing to paint, so go straight to the last step.
  3. Otherwise call the helper fill(image, sr, sc, original, color), which paints one pixel and spreads from it. Inside fill, return at once if row r or column c is outside the image, or if image[r][c] is not original.
  4. Paint image[r][c] with color, then call fill for the pixel below (r + 1), above (r - 1), to the right (c + 1) and to the left (c - 1).
  5. When the first call to fill returns, every reachable pixel is painted, and floodFill returns image.

The main method runs both examples, a start pixel boxed in by other colors, a one-pixel image, and a 4 by 4 image whose 1s form a winding path. A small print method writes each image row by row.

Java
public class FloodFill {

    public static int[][] floodFill(int[][] image, int sr, int sc, int color) {
        int original = image[sr][sc];
        if (original != color) {
            fill(image, sr, sc, original, color);   // equal colors skip this: nothing to do
        }
        return image;
    }

    private static void fill(int[][] image, int r, int c, int original, int color) {
        if (r < 0 || r >= image.length || c < 0 || c >= image[0].length) {
            return;                                 // outside the image
        }
        if (image[r][c] != original) {
            return;                                 // another color, or painted already
        }
        image[r][c] = color;                        // painting also marks the pixel as done
        fill(image, r + 1, c, original, color);     // down
        fill(image, r - 1, c, original, color);     // up
        fill(image, r, c + 1, original, color);     // right
        fill(image, r, c - 1, original, color);     // left
    }

    private static void print(String label, int[][] image) {
        System.out.println(label);
        for (int[] row : image) {
            StringBuilder line = new StringBuilder("  ");
            for (int value : row) {
                line.append(value).append(' ');
            }
            System.out.println(line.toString().stripTrailing());
        }
    }

    public static void main(String[] args) {
        int[][] example1 = {{1, 1, 1}, {1, 1, 0}, {1, 0, 1}};
        print("Example 1, start (1, 1), color 2:", floodFill(example1, 1, 1, 2));

        int[][] example2 = {{0, 0, 0}, {0, 0, 0}};
        print("Example 2, start (0, 0), color 0:", floodFill(example2, 0, 0, 0));

        int[][] boxedIn = {{1, 1, 1}, {1, 1, 0}, {1, 0, 1}};
        print("Example 1 image, start (1, 2), color 5:", floodFill(boxedIn, 1, 2, 5));

        int[][] onePixel = {{7}};
        print("One pixel, start (0, 0), color 3:", floodFill(onePixel, 0, 0, 3));

        int[][] winding = {
            {1, 1, 1, 1},
            {0, 0, 0, 1},
            {1, 1, 1, 1},
            {1, 0, 0, 0}
        };
        print("Winding path, start (0, 0), color 9:", floodFill(winding, 0, 0, 9));
    }
}

Running it prints:

Output
Example 1, start (1, 1), color 2:
  2 2 2
  2 2 0
  2 0 1
Example 2, start (0, 0), color 0:
  0 0 0
  0 0 0
Example 1 image, start (1, 2), color 5:
  1 1 1
  1 1 5
  1 0 1
One pixel, start (0, 0), color 3:
  3
Winding path, start (0, 0), color 9:
  9 9 9 9
  0 0 0 9
  9 9 9 9
  9 0 0 0

In the first block, row 2 ends in 1 while the six pixels joined to the start read 2, just like the teal pixels in the picture. The Example 2 block comes back all zeros and unchanged, because the color check skipped the fill.

The third block starts on the Example 1 image at row 1, col 2, a 0 whose neighbors are all 1 or outside the image, so that single pixel becomes 5 and nothing else changes. The one-pixel image simply turns from 7 to 3.

The last block is the winding path. From row 0, col 0 the 1s run right along row 0, down column 3, back left along row 2 and down to row 3, col 0, and all ten of them are now 9. Row 3, col 0 is only three rows below the start, yet the fill had to walk around the 0s in row 1 to get there.

The color check in floodFill is a guard worth keeping. A separate test program runs fill on Example 2 without it, and prints Example 2 without the guard: java.lang.StackOverflowError. Row 0, col 0 and row 1, col 0 keep calling each other until the call stack runs out of room, because painting 0 over 0 never marks either pixel as done.

Complexity

For an image with m rows and n columns, the cost depends on how many pixels get painted and how deep the chain of waiting calls grows.

  • Time: O(m × n), because each of the m × n pixels is painted at most once. Each painted pixel makes four calls, and a call that finds nothing to paint returns after its two checks.
  • Space: O(m × n) in the worst case, because on a winding path like the 4 by 4 image in main, every pixel painted so far waits on the call stack until the end of the path is reached.

Flood fill is the building block of Number of Islands.