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 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:
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 with 0, which is the same as the target color. Therefore, no changes are made to the image.
Constraints:
m == grid.lengthn == grid[i].length1 <= m, n <= 500 <= image[i][j], color < (2^16)0 <= sr < m0 <= sc < nclass Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]:
if image[sr][sc] == color:
return image
m, n = len(image), len(image[0])
dirs = [1,0,-1,0,1]
def dfs(r, c, org):
if not (0 <= r < m) or not (0 <= c < n) or image[r][c] != org:
return
image[r][c] = color
for d in range(4):
dfs(r + dirs[d], c + dirs[d + 1], org)
dfs(sr, sc, image[sr][sc])
return imageWhere is the number of rows and is the number of columns in the image.
class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]:
orig = image[sr][sc]
if orig == color:
return image
m, n = len(image), len(image[0])
q = deque([(sr, sc)])
image[sr][sc] = color
dirs = [(1,0), (-1,0), (0,1), (0,-1)]
while q:
r, c = q.popleft()
for dr, dc in dirs:
nr, nc = r + dr, c + dc
if 0 <= nr < m and 0 <= nc < n and image[nr][nc] == orig:
image[nr][nc] = color
q.append((nr, nc))
return imageWhere is the number of rows and is the number of columns in the image.