BFS
def floodFill(self, image, sr, sc, newColor):
"""
:type image: List[List[int]]
:type sr: int
:type sc: int
:type newColor: int
:rtype: List[List[int]]
"""
cur = image[sr][sc]
if cur == newColor:
return image
row , col = len(image)-1,len(image[0])-1
que = collections.deque([(sr, sc)])
image[sr][sc] = newColor
while que:
x,y = que.popleft()
for nx,ny in [(x+1,y),(x-1,y),(x,y+1),(x,y-1)]:
if 0 <= nx <= row and 0 <= ny <= col and image[nx][ny] == cur:
image[nx][ny] = newColor
que.append((nx,ny))
return image
DFS
class Solution(object):
def floodFill(self, image, sr, sc, newColor):
"""
:type image: List[List[int]]
:type sr: int
:type sc: int
:type newColor: int
:rtype: List[List[int]]
"""
cur = image[sr][sc]
row , col = len(image)-1,len(image[0])-1
def backtrack(x,y):
image[x][y] = newColor
for nx,ny in [(x+1,y),(x-1,y),(x,y+1),(x,y-1)]:
if 0 <= nx <= row and 0 <= ny <= col and image[nx][ny] == cur:
backtrack(nx,ny)
if cur != newColor:
backtrack(sr,sc)
return image