通过 dfs(i, j, time) 的寻路方式来寻找可行的路径当 grid[i][j] <= time + 3 时说明 time 时刻 grid[i][j] 会着火,因此不能进行移动,除非它是终点
classSolution:defmaximumMinutes(self, grid: List[List[int]])->int:fire =[]m =len(grid)n =len(grid[0])for i inrange(m):for j inrange(n):if grid[i][j]==1:fire.append([i, j])grid[i][j]=3t =4whilelen(fire)>0:for _ inrange(len(fire)):f = fire.pop(0)if f[0]+1< m and grid[f[0]+1][f[1]]==0:fire.append([f[0]+1, f[1]])grid[f[0]+1][f[1]]= tif f[0]-1>=0and grid[f[0]-1][f[1]]==0:fire.append([f[0]-1, f[1]])grid[f[0]-1][f[1]]= tif f[1]+1< n and grid[f[0]][f[1]+1]==0:fire.append([f[0], f[1]+1])grid[f[0]][f[1]+1]= tif f[1]-1>=0and grid[f[0]][f[1]-1]==0:fire.append([f[0], f[1]-1])grid[f[0]][f[1]-1]= tt +=1vis =[[0]* n for _ inrange(m)]@cachedeffind(i, j, time):if grid[i][j]==2or(grid[i][j]!=0and grid[i][j]<= time +3):if i == m -1and j == n -1and grid[i][j]== time +3:returnTruereturnFalseif i == m -1and j == n -1:returnTruevis[i][j]=1if i +1< m and vis[i +1][j]==0and find(i +1, j, time +1)\or i >0and vis[i -1][j]==0and find(i -1, j, time +1)\or j +1< n and vis[i][j +1]==0and find(i, j +1, time +1)\or j >0and vis[i][j -1]==0and find(i, j -1, time +1):returnTruevis[i][j]=0returnFalseif find(0,0, t):return10**9vis =[[0]* n for _ inrange(m)]if find(0,0,0)isFalse:return-1l, r =0, t -3while l < r -1:mid =(l + r)>>1vis =[[0]* n for _ inrange(m)]if find(0,0, mid):l = midelse:r = midreturn l