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, imageimage[r][c]rcsrsccolor
Example 1
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
Output: [[0, 0, 0], [0, 0, 0]]
Explanation: the new color is the same as the old one, so nothing changes.
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.
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
Because fill
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
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
Java Solution
The method floodFill
- First, read the start pixel's color into
withoriginal .image[sr][sc] - If
equalsoriginal , there is nothing to paint, so go straight to the last step.color - Otherwise call the helper
, which paints one pixel and spreads from it. Insidefill(image, sr, sc, original, color) , return at once if rowfill or columnr is outside the image, or ifc is notimage[r][c] .original - Paint
withimage[r][c] , then callcolor for the pixel below (fill ), above (r + 1 ), to the right (r - 1 ) and to the left (c + 1 ).c - 1 - When the first call to
returns, every reachable pixel is painted, andfill returnsfloodFill .image
The mainprint
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:
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 12
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 53
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
The color check in floodFillfillExample 2 without the guard: java.lang.StackOverflowError
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
, every pixel painted so far waits on the call stack until the end of the path is reached.main
Flood fill is the building block of