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.
1class Solution {
2 public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
3 int originalColor = image[sr][sc];
4 if (originalColor != newColor) {
5 dfs(image, sr, sc, originalColor, newColor);
6 }
7 return image;
8 }
9
10 private void dfs(int[][] image, int r, int c, int originalColor, int newColor) {
11 if (r < 0 || r >= image.length || c < 0 || c >= image[0].length || image[r][c] != originalColor)
12 return;
13 image[r][c] = newColor;
14 dfs(image, r + 1, c, originalColor, newColor);
15 dfs(image, r - 1, c, originalColor, newColor);
16 dfs(image, r, c + 1, originalColor, newColor);
17 dfs(image, r, c - 1, originalColor, newColor);
18 }
19}
In this Java implementation, we define a helper method dfs
which maintains the logic and conditions necessary to perform the DFS flood fill.
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.
1from collections import deque
2
3def flood_fill(image, sr, sc, new_color):
4 original_color = image[sr][sc]
5 if original_color == new_color:
6 return image
7
8 rows, cols = len(image), len(image[0])
9 queue = deque([(sr, sc)])
10 directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]
11
12 while queue:
13 r, c = queue.popleft()
14 if image[r][c] == original_color:
15 image[r][c] = new_color
16 for dr, dc in directions:
17 rr, cc = r + dr, c + dc
18 if 0 <= rr < rows and 0 <= cc < cols and image[rr][cc] == original_color:
19 queue.append((rr, cc))
20
21 return image
This Python solution uses a queue to implement the BFS process, iterating over each pixel and its adjacent pixels. The queue ensures all connected pixels are enqueued and processed correctly.