通过 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]=3
t =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]]= t
if f[0]-1>=0and grid[f[0]-1][f[1]]==0:
fire.append([f[0]-1, f[1]])
grid[f[0]-1][f[1]]= t
if 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]= t
if f[1]-1>=0and grid[f[0]][f[1]-1]==0:
fire.append([f[0], f[1]-1])
grid[f[0]][f[1]-1]= t
t +=1
vis =[[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:returnTrue
vis[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):returnTrue
vis[i][j]=0returnFalseif find(0,0, t):return10**9
vis =[[0]* n for _ inrange(m)]if find(0,0,0)isFalse:return-1
l, r =0, t -3while l < r -1:
mid =(l + r)>>1
vis =[[0]* n for _ inrange(m)]if find(0,0, mid):
l = mid
else:
r = mid
return l
[python 刷题] 437 Path Sum III
之前有写过 Path Sum I & II, leetcode 112 & 113,虽然使用 JS 写的,不过 python 的实现也更新了一下
题目如下: Given the root of a binary tree and an integer targetSum, return the number o…