class Solution: def orangesRotting(self, grid: list[list[int]]) -> int: m,n=len(grid),len(grid[0]) queue,good=[],[] def bfs(queue,good,m,n,grid): times=0 directions=[(-1,0),(1,0),(0,1),(0,-1)] while queue: tmp=len(queue) #print(queue,times) for t in range(tmp) : i=queue[0] for j in directions: tmp1=i[0]+j[0] tmp2=i[1]+j[1] if 0<=tmp1<m and 0<=tmp2<n and grid[tmp1][tmp2]==1 : grid[tmp1][tmp2]=2 queue.append((tmp1,tmp2)) good.remove((tmp1,tmp2)) queue.pop(0) times+=1 if good: return -1 return times-1 for i in range(m): for j in range(n): if grid[i][j]==2: queue.append((i,j)) elif grid[i][j]==1: good.append((i,j)) if not good: return 0 elif not queue: return -1 return bfs(queue,good,m,n,grid) try: solution=Solution() grid=[[2,1,1],[1,1,0],[0,1,1]] res=solution.orangesRotting(grid) print(res) except: print('error')
标签:tmp,994,int,queue,len,bfs,grid,题库 From: https://www.cnblogs.com/tanyuanqing/p/17660167.html