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.
1#include <stdio.h>
2
3void dfs(int** image, int m, int n, int r, int c, int originalColor, int newColor) {
4 if (r < 0 || r >= m || c < 0 || c >= n || image[r][c] != originalColor) return;
5 image[r][c] = newColor;
6 dfs(image, m, n, r + 1, c, originalColor, newColor);
7 dfs(image, m, n, r - 1, c, originalColor, newColor);
8 dfs(image, m, n, r, c + 1, originalColor, newColor);
9 dfs(image, m, n, r, c - 1, originalColor, newColor);
10}
11
12int** floodFill(int** image, int m, int n, int sr, int sc, int color, int* returnSize, int** returnColumnSizes) {
13 int originalColor = image[sr][sc];
14 if (originalColor != color) {
15 dfs(image, m, n, sr, sc, originalColor, color);
16 }
17 return image;
18}
This C solution implements DFS similarly to the Python version but requires direct pointer manipulations and array index bounds checking.
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.