733. 图像渲染
733. 图像渲染 - 力扣(LeetCode) (leetcode-cn.com)https://leetcode-cn.com/problems/flood-fill/
思路:
1.广度优先搜索
(1)从一个格子出发,将其所对应的下表元组加入一个空列表,并将其颜色修改
(2)按照一个固定的顺序遍历其上下左右的所有格子
(3)如果格子内和初始格子的值相同,则将其格子对应的下表元组加入列表,并修改它对应的值为目标值
(4)每次从列表中取出一个来作为当前格子,反复操作直到列表为空为止。
(5)列表弹出最好用collections模块当中的deque结构,实现先进先出的队列结构
2.深度优先搜索
(1)从一个格子出发,将其颜色修改
(2)向某一个方向一直前进,直到达到格子边界
(3)过程中如果遇到了和初始颜色相同的格子,则将其颜色改变,否则继续前进
(4)可以设置一个函数来执行上述过程
代码:
1.广度:
class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:
nowColor = image[sr][sc]
if nowColor == newColor:
return image
m, n = len(image), len(image[0]) #获取行列数
que = collections.deque([(sr, sc)])
image[sr][sc] = newColor
while que:
x, y = que.popleft()
for mx, ny in [(x+1, y), (x-1, y), (x,y-1), (x, y+1)]:
if 0 <= mx < m and 0 <= ny < n and image[mx][ny] == nowColor :
que.append((mx, ny))
image[mx][ny] = newColor
print(mx,ny)
return image
2.深度:
class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:
m, n = len(image), len(image[0])
nowColor = image[sr][sc]
def DFS(x, y):
if image[x][y] == nowColor:
image[x][y] = newColor
for mx, ny in[(x+1, y), (x-1, y), (x, y-1), (x, y+1)]:
if 0<=mx<m and 0<=ny<n and image[mx][ny] == nowColor:
DFS(mx, ny)
if nowColor != newColor:
DFS(sr, sc)
return image