This approach uses recursion to explore all connected pixels that need to be updated. Starting from the initial pixel, you recursively attempt to update all four possible directions (up, down, left, right) whenever the neighboring pixel has the same original color.
The recursion ensures that all connected and valid pixels are eventually updated. Make sure to handle the base case where the function stops if the pixel is out of bounds or if it doesn't need updating (either because it's already updated or has a different color).
Time Complexity: O(m * n) because in the worst case, all of the pixels will be connected and thus changed.
Space Complexity: O(m * n) due to the recursion call stack.
1def flood_fill(image, sr, sc, new_color):
2 original_color = image[sr][sc]
3 if original_color == new_color: return image
4
5 def dfs(r, c):
6 if r < 0 or r >= len(image) or c < 0 or c >= len(image[0]) or image[r][c] != original_color:
7 return
8 image[r][c] = new_color
9 dfs(r + 1, c)
10 dfs(r - 1, c)
11 dfs(r, c + 1)
12 dfs(r, c - 1)
13
14 dfs(sr, sc)
15 return image
In this Python solution, we define a recursive function dfs
which updates the color of a pixel and then recursively calls itself for each adjacent pixel. The function checks boundary conditions and whether the pixel is of the original color before updating it.
This approach employs an iterative breadth-first search (BFS) using a queue. Starting from the initial pixel, we enqueue it and begin the BFS process, updating connected pixels of the same original color to the new color.
For each pixel, check its adjacent pixels and enqueue them if they are valid and of the original color. This continues until the queue is empty, ensuring all pixels are updated appropriately.
Time Complexity: O(m * n), where m and n are the dimensions of the image (same as DFS).
Space Complexity: O(m * n), as we may store all pixels in the queue in the worst-case scenario.
1import java.util.LinkedList;
2import java.util.Queue;
3
4class Solution {
5 public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
6 int originalColor = image[sr][sc];
7 if (originalColor == newColor) return image;
8
9 int rows = image.length;
10 int cols = image[0].length;
11 Queue<int[]> queue = new LinkedList<>();
12 queue.offer(new int[]{sr, sc});
13
14 int[][] directions = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
15
16 while (!queue.isEmpty()) {
17 int[] cell = queue.poll();
18 int r = cell[0], c = cell[1];
19 if (image[r][c] == originalColor) {
20 image[r][c] = newColor;
21 for (int[] d : directions) {
22 int rr = r + d[0], cc = c + d[1];
23 if (rr >= 0 && rr < rows && cc >= 0 && cc < cols && image[rr][cc] == originalColor) {
24 queue.offer(new int[]{rr, cc});
25 }
26 }
27 }
28 }
29
30 return image;
31 }
32}
This Java solution utilizes a LinkedList
to create a queue, following a BFS strategy to update pixel colors and exploring adjacent pixels iteratively.