You are given an image represented by an m x n
grid of integers image
, where image[i][j]
represents the pixel value of the image. You are also given three integers sr
, sc
, and color
. Your task is to perform a flood fill on the image starting from the pixel image[sr][sc]
.
To perform a flood fill:
color
.Return the modified image after performing the flood fill.
Example:
Consider the following image: [[1,1,1],[1,1,0],[1,0,1]]
. If we start at sr = 1
, sc = 1
, and want to change the color to color = 2
, the expected output is [[2,2,2],[2,2,0],[2,0,1]]
. The algorithm starts at the center pixel (value 1) and changes it to 2. Then, it recursively updates all adjacent pixels with the original color (1) to the new color (2). The bottom corner is not updated because it is not connected to the starting pixel via a path of 1's.
How would you implement an efficient algorithm to solve the flood fill problem, taking into consideration time and space complexity, and potential edge cases?
A brute-force approach to solving the flood fill problem would involve recursively checking all adjacent pixels and changing their color if they match the original color. This method is straightforward but may lead to stack overflow errors for very large images due to excessive recursion.
def floodFill_brute_force(image, sr, sc, color):
if image[sr][sc] == color:
return image
def fill(image, r, c, original_color, new_color):
if r < 0 or r >= len(image) or c < 0 or c >= len(image[0]) or image[r][c] != original_color:
return
image[r][c] = new_color
fill(image, r + 1, c, original_color, new_color)
fill(image, r - 1, c, original_color, new_color)
fill(image, r, c + 1, original_color, new_color)
fill(image, r, c - 1, original_color, new_color)
original_color = image[sr][sc]
fill(image, sr, sc, original_color, color)
return image
The optimal solution also uses a recursive approach (Depth-First Search), but it's crucial to manage the recursion effectively to avoid stack overflow issues. The algorithm remains the same but is optimized for clarity and efficiency.
def floodFill(image, sr, sc, color):
if image[sr][sc] == color:
return image
rows, cols = len(image), len(image[0])
original_color = image[sr][sc]
def dfs(row, col):
if row < 0 or row >= rows or col < 0 or col >= cols or image[row][col] != original_color:
return
image[row][col] = color
dfs(row + 1, col)
dfs(row - 1, col)
dfs(row, col + 1)
dfs(row, col - 1)
dfs(sr, sc)
return image
1 <= m, n <= 50
, the code should ideally handle an empty image gracefully (though this is not strictly required by the problem description).The flood fill algorithm is effectively implemented using Depth-First Search (DFS). The key is to recursively update adjacent pixels of the same color until no more updates are possible. The time complexity is O(m * n), and the space complexity depends on the depth of the recursion, which in the worst case can be O(m * n).