classSolution: defmaximumMinutes(self, grid: List[List[int]]) -> int: n = len(grid) m = len(grid[0]) dx = [1, -1, 0, 0] dy = [0, 0, 1, -1]
# 预处理 f # f[i][j] := (i, j) 有火的时间,即最短路径的距离 f = [[int(1e9) for _ in range(m)] for _ in range(n)] q = Queue() # 队列中的内容:i, j for i in range(n): for j in range(m): if grid[i][j] == 1: f[i][j] = 0 q.put((i, j)) whilenot q.empty(): i, j = q.get() t = f[i][j] for d in range(4): nxt_i = i + dx[d] nxt_j = j + dy[d] if nxt_i < 0or nxt_i >= n or nxt_j < 0or nxt_j >= m: continue if grid[nxt_i][nxt_j] != 0: continue if f[nxt_i][nxt_j] != int(1e9): continue f[nxt_i][nxt_j] = t + 1 q.put((nxt_i, nxt_j))
# 一条路径一条路径考查 ans = [-1] # ans 引用传递 p = [[int(1e9) for _ in range(m)] for _ in range(n)] defdfs(i: int, j: int, delta: int) -> None: # delta 值传递 Delta = f[i][j] - p[i][j] if (i, j) == (n - 1, m - 1): if Delta < 0: return delta = min(delta, Delta) # 找到一条通关路径 ans[0] = max(ans[0], delta) return
if Delta <= 0: # 可行性剪枝 return delta = min(delta, Delta - 1) if delta <= ans[0]: # 最优性剪枝 return
for d in range(4): nxt_i = i + dx[d] nxt_j = j + dy[d] if nxt_i < 0or nxt_i >= n or nxt_j < 0or nxt_j >= m: continue if grid[nxt_i][nxt_j] != 0: continue if p[i][j] + 1 > p[nxt_i][nxt_j]: continue p[nxt_i][nxt_j] = p[i][j] + 1 dfs(nxt_i, nxt_j, delta)
p[0][0] = 0 dfs(0, 0, int(2e9))
if ans[0] > int(1e8): return int(1e9) return ans[0]
classSolution: defmaximumMinutes(self, grid: List[List[int]]) -> int: n = len(grid) m = len(grid[0]) dx = [1, -1, 0, 0] dy = [0, 0, 1, -1]
defbfs(ps: List[Tuple[int, int]]): # BFS 最短路径 f = [[int(1e9) for _ in range(m)] for _ in range(n)] q = Queue() # 队列中的内容:i, j for s in ps: f[s[0]][s[1]] = 0 q.put((s[0], s[1])) whilenot q.empty(): i, j = q.get() t = f[i][j] for d in range(4): nxt_i = i + dx[d] nxt_j = j + dy[d] if nxt_i < 0or nxt_i >= n or nxt_j < 0or nxt_j >= m: continue if grid[nxt_i][nxt_j] != 0: continue if f[nxt_i][nxt_j] != int(1e9): continue f[nxt_i][nxt_j] = t + 1 q.put((nxt_i, nxt_j)) return f
# 预处理 f # f[i][j] := (i, j) 有火的时间,即最短路径的距离 source_points = [] for i in range(n): for j in range(m): if grid[i][j] == 1: source_points.append((i, j)) f = bfs(source_points)