Solution 1: Breadth-first search
def flood_fill(image, row, col, color)
m, n = image.length, image[0].length
old_color = image[row][col]
return image if old_color == color
queue = []
queue << [row, col]
while queue.length > 0
row, col = queue.shift
next if image[row][col] != old_color
image[row][col] = color
queue << [row-1, col] if row-1 >= 0
queue << [row+1, col] if row+1 <= m-1
queue << [row, col-1] if col-1 >= 0
queue << [row, col+1] if col+1 <= n-1
end
image
end
Time |
O(mn) |
Checking up to every pixel in the image |
Space |
O(mn) |
Queue size |
Solution 2: Depth-first search
def flood_fill(image, row, col, color)
m, n = image.length, image[0].length
old_color = image[row][col]
return image if old_color == color
dfs = lambda do |row, col|
return if row < 0 || row >= m
return if col < 0 || col >= n
return if image[row][col] != old_color
image[row][col] = color
dfs.call(row-1, col)
dfs.call(row+1, col)
dfs.call(row, col-1)
dfs.call(row, col+1)
end
dfs.call(row, col)
image
end
Time |
O(mn) |
Checking up to every pixel in the image |
Space |
O(mn) |
Stack depth |