class Solution:
def shortestPath(self, grid: List[List[int]], k: int) -> int:
n = len(grid)
m = len(grid[0])
if n == 1 and m == 1:
return 0
visited = [[[0] * (k + 1) for _ in range(m)] for _ in range(n)]
queue = [[0, 0, k, 0]]
direction = [[1, 0], [-1, 0], [0, 1], [0, -1]]
while queue:
x, y, f, s = queue.pop(0)
for p, q in direction:
next_x = x + p
next_y = y + q
if 0 <= next_x < n and 0 <= next_y < m:
if next_x == n - 1 and next_y == m - 1:
return s + 1
# 如果下一个位置是墙,必须保证还有破墙术,
# 并且我们必须保证之前没有路径访问过这个位置的时候剩余的破墙数等于当前路径剩余的破墙术,
# 更不能容忍之前路径剩余的破墙术大于当前路径剩余的破墙术,
# 上面两种情况下,当前路径是不可能比之前路径更快的
if (
grid[next_x][next_y] == 1
and f > 0
and sum(visited[next_x][next_y][f - 1 :]) == 0
):
queue.append([next_x, next_y, f - 1, s + 1])
visited[next_x][next_y][f - 1] = 1
elif (
grid[next_x][next_y] == 0
and sum(visited[next_x][next_y][f:]) == 0
):
queue.append([next_x, next_y, f, s + 1])
visited[next_x][next_y][f] = 1
return -1
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?