Flood Fill (LeetCode 733): Solution and Explanation
Given an image as a grid of pixel values, a starting pixel and a new color, recolor the starting pixel and every pixel connected to it through up, down, left and right moves that shares its original color. Return the image.
Intuition
Think of the image as a graph. Each pixel is a node, and it has an edge to each of its four neighbours. The pixels to recolor are exactly the connected region of the starting pixel's original color.
Finding a connected region is a plain graph search. DFS or BFS from the start pixel, and only step into neighbours that still have the original color. Pixels of any other color act as walls.
No separate visited set is needed. Painting a pixel the moment it is pushed changes its color, so it will never match the original color again and can never be pushed twice. That trick fails only when the new color equals the old one, so that case returns right away.
Approach: Iterative DFS with paint-on-push
- Save
old = image[sr][sc]. Ifold == color, return the image unchanged. - Paint
image[sr][sc]withcolorand push(sr, sc)onto a stack. - Pop a pixel. For each of its four neighbours that is inside the image and still equals
old, paint it and push it. - When the stack is empty, every pixel of the region has been painted. Return the image.
Step-by-step example
image = [[1,1,1],[1,1,0],[1,0,1]], sr = 1, sc = 1, color = 2
- The start pixel (1,1) has color 1. Paint it 2 and push it.
- Pop (1,1). Its neighbours (0,1) and (1,0) are 1, so both are painted and pushed. (2,1) and (1,2) are 0, which are walls.
- Popping (1,0) paints (2,0) and (0,0). Popping (0,0) and (2,0) adds nothing. Popping (0,1) paints (0,2), and popping (0,2) finds only the 0 at (1,2) below it.
- The stack empties. The bottom-right 1 only touches the region diagonally, so it is never reached. The result is [[2,2,2],[2,2,0],[2,0,1]].
Code: Python, Java, C++
1class Solution:
2 def floodFill(self, image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]:
3 old = image[sr][sc]
4 if old == color:
5 return image
6 m, n = len(image), len(image[0])
7 stack = [(sr, sc)]
8 image[sr][sc] = color
9 while stack:
10 r, c = stack.pop()
11 for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
12 if 0 <= nr < m and 0 <= nc < n and image[nr][nc] == old:
13 image[nr][nc] = color
14 stack.append((nr, nc))
15 return image1class Solution {
2 public int[][] floodFill(int[][] image, int sr, int sc, int color) {
3 int old = image[sr][sc];
4 if (old == color) {
5 return image;
6 }
7 int m = image.length, n = image[0].length;
8 Deque<int[]> stack = new ArrayDeque<>();
9 stack.push(new int[]{sr, sc});
10 image[sr][sc] = color;
11 int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
12 while (!stack.isEmpty()) {
13 int[] cell = stack.pop();
14 for (int[] d : dirs) {
15 int nr = cell[0] + d[0], nc = cell[1] + d[1];
16 if (nr >= 0 && nr < m && nc >= 0 && nc < n && image[nr][nc] == old) {
17 image[nr][nc] = color;
18 stack.push(new int[]{nr, nc});
19 }
20 }
21 }
22 return image;
23 }
24}1class Solution {
2public:
3 vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int color) {
4 int old = image[sr][sc];
5 if (old == color) {
6 return image;
7 }
8 int m = image.size(), n = image[0].size();
9 vector<pair<int, int>> st = {{sr, sc}};
10 image[sr][sc] = color;
11 int dirs[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
12 while (!st.empty()) {
13 auto [r, c] = st.back();
14 st.pop_back();
15 for (auto& d : dirs) {
16 int nr = r + d[0], nc = c + d[1];
17 if (nr >= 0 && nr < m && nc >= 0 && nc < n && image[nr][nc] == old) {
18 image[nr][nc] = color;
19 st.push_back({nr, nc});
20 }
21 }
22 }
23 return image;
24 }
25};Time and space complexity
O(m * n)
Each pixel is painted and pushed at most once, and each pop checks four neighbours.
O(m * n)
In the worst case, such as an image of a single color, the stack can hold a large share of the pixels.
Other approaches
Recursive DFS (time O(m * n), space O(m * n) call stack)
Paint the pixel, then call the function on its four neighbours when they match the old color. It is the shortest code, but a 50 x 50 single-color image can recurse 2,500 levels deep, which is close to Python's default limit.
BFS with a queue (time O(m * n), space O(m * n))
Same paint-on-push rule, but with a queue. The region fills outward in rings around the start pixel instead of following one branch to its end. The cost is identical.
Common mistakes
- Forgetting the
old == colorcheck. Painted pixels still match the old color, so the search pushes the same pixels forever. - Reading the old color after painting the start pixel. Save it first.
- Spreading diagonally. Only the four edge neighbours count.
- Comparing neighbours with the new color instead of the old one, which stops the fill at the first step.
Frequently asked questions
Why do I need the check for old color equal to new color?
The algorithm uses the new color as its visited mark. When both colors are the same, painting marks nothing, and pixels keep being pushed again. Returning early fixes it, and it is also correct because nothing would change.
Should I use DFS or BFS?
Either works with the same cost. They only change the order in which pixels are painted. An explicit stack or queue avoids recursion depth limits on large single-color images.
Is this related to Number of Islands?
Yes. Number of Islands runs this same fill from every unvisited land cell and counts how many fills it starts. Flood Fill is a single fill from a given start.
What is the time complexity of flood fill?
O(m * n). Each pixel is painted at most once and checks four neighbours, so the work is linear in the size of the image.