[Python手撕]网格中的最短路径(可以有k次破墙的机会)(bfs)

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

作者:Esofar

出处:https://www.cnblogs.com/DCFV/p/18444518

版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。

posted @   Duancf  阅读(6)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
more_horiz
keyboard_arrow_up dark_mode palette
选择主题
点击右上角即可分享
微信分享提示