文巾解题 733. 图像渲染
生活随笔
收集整理的這篇文章主要介紹了
文巾解题 733. 图像渲染
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1 題目描述
2 解題思路
注意一點,如果第一個要渲染的點,顏色和要渲染成的顏色是一樣的,那么我們直接返回。不然的話會死循環。
2.1 廣度優先遍歷?
廣搜是使用隊列來實現的
class Solution:def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:row=len(image)column=len(image[0])color=image[sr][sc]if(image[sr][sc]==newColor):return image #特判不需要任何修改的情況image[sr][sc]=newColorlst=[(sr,sc)]while(lst):print(lst)tmp_x,tmp_y=lst.pop(0)for x,y in [(tmp_x-1,tmp_y),(tmp_x+1,tmp_y),(tmp_x,tmp_y-1),(tmp_x,tmp_y+1)]:if(x>=0 and x<row and y>=0 and y<column):if(image[x][y]==color):image[x][y]=newColorlst.append((x,y))return(image)2.2 深度優先遍歷
深搜是使用遞歸來實現的
class Solution:def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:row=len(image)column=len(image[0])color=image[sr][sc]if(image[sr][sc]==newColor):return image #特判不需要渲染的情況image[sr][sc]=newColordef dfs(x,y):for (i,j) in [(x-1,y),(x+1,y),(x,y-1),(x,y+1)]:if(i>=0 and i < row and j>=0 and j<column):if(image[i][j]==color):image[i][j]=newColordfs(i,j)dfs(sr,sc)return image總結
以上是生活随笔為你收集整理的文巾解题 733. 图像渲染的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ntu 医疗
- 下一篇: 文巾解题 695. 岛屿的最大面积