Flood Fill
733. Flood Fill
Difficulty: Easy
Related Topics: Array, DFS, BFS, Matrix
An image is represented by an m x n integer grid image where image[i][j] represents the pixel value of the image.
You are also given three integers sr, sc, and color. You should perform a flood fill on the image starting from the pixel image[sr][sc].
To perform a flood fill, consider the starting pixel, plus any pixels connected 4-directionally to the starting pixel of the same color as the starting pixel, plus any pixels connected 4-directionally to those pixels (also with the same color), and so on. Replace the color of all of the aforementioned pixels with color.
Return the modified image after performing the flood fill.
Example 1:
Input: image = [[1,1,1],[1,1,0],[1,0,1]], sr = 1, sc = 1, color = 2 Output: [[2,2,2],[2,2,0],[2,0,1]] Explanation: From the center of the image with position (sr, sc) = (1, 1) (i.e., the red pixel), all pixels connected by a path of the same color as the starting pixel (i.e., the blue pixels) are colored with the new color. Note the bottom corner is not colored 2, because it is not 4-directionally connected to the starting pixel.
Example 2:
Input: image = [[0,0,0],[0,0,0]], sr = 0, sc = 0, color = 0 Output: [[0,0,0],[0,0,0]] Explanation: The starting pixel is already colored 0, so no changes are made to the image.
First Attempt:
Code:
class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]:
first_color = image[sr][sc]
direction = [(-1,0),(1,0),(0,-1),(0,1)]
def dfs(sr, sc, color):
newImage = [[-1 for _ in range(len(image[0]))] for _ in range(len(image))]
stack =[]
stack.append((sr,sc))
while stack:
curr = stack.pop()
if newImage[curr[0]][curr[1]] == color: continue
newImage[curr[0]][curr[1]] = color
image[curr[0]][curr[1]] = color
for i in range(4):
nr = curr[0] + direction[i][0]
nc = curr[1] + direction[i][1]
if nr < 0 or nr > len(image)-1 or nc < 0 or nc > len(image[0])-1 :
continue
if newImage[nr][nc] == color: continue
if image[nr][nc] != first_color: continue
stack.append((nr, nc))
dfs(sr, sc, color)
return image
Feedbacks:
I made DFS function to search through every plates and find other lands which have same starting-color as the starting pixels. Once I found surrounding plates having same color as starting pixel, I make change on the original image plate. So when I return after the while loop of DFS function, I can get the updated version of image which is an answer. This was my first DFS question. Should work more on DFS since it is only easy difficulty problem, and work on BFS as well.