跳至内容
994. 腐烂的橘子
- class Solution:
- def orangesRotting(self, grid: List[List[int]]) -> int:
- row=len(grid)
- col=len(grid[0])
- que=deque()
- for i in range(row):
- for j in range(col):
- if grid[i][j]==2:
- que.append((i,j))
- res=0
- direction=[(0,1),(0,-1),(1,0),(-1,0)]
- while que: #有坏橘子则循环
- is_=False
- size=len(que)
- for i in range(size): #在某一层bfs
- r,c=que.popleft()
- for x,y in direction: #上下左右四橘子的情况
- dr=r+x
- dc=y+c
- if 0<=dr<row and 0<=dc<col and grid[dr][dc]==1:#判断是否出界,是否新鲜
- grid[dr][dc]=2
- que.append((dr,dc)) #被感染的橘子添加到队列里
- is_=True
- if is_:
- res+=1 #如果一层橘子已经腐烂,没有必要再计时+1
- for i in range(row):
- for j in range(col):
- if grid[i][j]==1:
- res=-1 #最后检查有无不能被感染的橘子
- return res