【题目】



【代码】
【方法1】栈模拟深度优先遍历
就是用栈代替dfs,注意这里如果image[sr][sc]==color程序直接结束,返回原始的image
因为图像渲染就是将原始颜色渲染成新颜色,如果前后颜色相同就没必要渲染,如果不单独判断前后颜色是否相同,直接对图像进行颜色变换,会导致死循环,如果不想判断,那必须记录已经访问过的节点的信息,不重复访问已经访问的节点

class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]:
stack=[(sr,sc)]
origin=image[sr][sc]
if origin==color:
return image
while stack:
sr,sc=stack.pop()
if 0<=sr<len(image) and 0<=sc<len(image[0]):
if image[sr][sc]==origin:
image[sr][sc]=color
stack.append((sr-1,sc))
stack.append((sr+1,sc))
stack.append((sr,sc+1))
stack.append((sr,sc-1))
return image
【方法2】dfs

class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]:
stack=[(sr,sc)]
origin=image[sr][sc]
if origin==color:
return image
def dfs(sr,sc):
if 0<=sr<len(image) and 0<=sc<len(image[0]):
if image[sr][sc]==origin:
image[sr][sc]=color
dfs(sr-1,sc)
dfs(sr+1,sc)
dfs(sr,sc+1)
dfs(sr,sc-1)
dfs(sr,sc)
return image
【方法4】

class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]:
queue=[(sr,sc)]
origin=image[sr][sc]
if origin==color:
return image
while queue:
sr,sc=queue.pop(0)
if 0<=sr<len(image) and 0<=sc<len(image[0]):
if image[sr][sc]==origin:
image[sr][sc]=color
queue.append((sr-1,sc))
queue.append((sr+1,sc))
queue.append((sr,sc+1))
queue.append((sr,sc-1))
return image
11万+

被折叠的 条评论
为什么被折叠?



