LC 0733 [E] Flood Fill
Code with Senpai edited this page Jul 2, 2022
·
2 revisions
class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, NEW_COLOR: int) -> List[List[int]]:
START_COLOR = image[sr][sc]
# visited = set() # use already color as visited set
def dfs(r, c):
# visited.add((r,c))
image[r][c] = NEW_COLOR
for dr, dc in [(0,1),(0,-1),(1,0),(-1,0)]:
nr = r + dr
nc = c + dc
if 0 <= nr < len(image) and 0 <= nc < len(image[0]):
if image[nr][nc] != NEW_COLOR: # not in visited
if image[nr][nc] == START_COLOR:
dfs(nr, nc)
dfs(sr, sc)
return image
# def floodFill(self, image: List[List[int]], sr: int, sc: int, NEW_COLOR: int) -> List[List[int]]:
# ROWS, COLS = len(image), len(image[0])
# START_COLOR = image[sr][sc]
# def dfs(i, j):
# if i < 0 or i>=ROWS or j < 0 or j >= COLS:
# return
# if image[i][j] == NEW_COLOR or image[i][j] != START_COLOR:
# return
# image[i][j] = NEW_COLOR
# dfs(i+1, j)
# dfs(i-1, j)
# dfs(i,j+1)
# dfs(i, j-1)
# dfs(sr, sc)
# return image
footer