E-733. Flood Fill
# 起始颜色不和新色相同,并且
# 相邻颜色和旧色相同
# 并且都在有效范围内,则染色。
# O(N), O(N)
class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:
def change_color(sr, sc):
if image[sr][sc] == old_color:
image[sr][sc] = newColor
if sr > 0:
change_color(sr - 1, sc)
if sr < max_row:
change_color(sr + 1, sc)
if sc < max_col:
change_color(sr, sc + 1)
if sc > 0:
change_color(sr, sc - 1)
old_color = image[sr][sc]
max_row = len(image)-1
max_col = len(image[0]) - 1
if sr >= 0 and sr <= max_row and sc >= 0 and sc <= max_col and image[sr][sc] != newColor :
change_color(sr, sc)
return image
Last updated
Was this helpful?