[leetcode]1293. 网格中的最短路径

13 篇文章 1 订阅
9 篇文章 0 订阅

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

struct Node
{
    int x, y;
    int rest;  //还可以消几个障碍物
    int dist;  //距离
    Node(int _x,int _y, int _rest, int _dist)
    	:x(_x), y(_y), rest(_rest),dist(_dist){}
};

class Solution {
    static constexpr int dx[4] = {-1, 0, 1, 0};     //上右下左
    static constexpr int dy[4] = { 0, 1, 0,-1};
public:
    int shortestPath(vector<vector<int>>& grid, int k) {
        int m = grid.size();
        int n = grid[0].size();
        if(n == 1 && m == 1)
        {
            return 0;
        }

        k = min(m + n -3, k);
        bool visited[m][n][k+1];
        memset(visited, false, sizeof(visited));
        queue<Node>q;
        q.push(Node(0,0,k,0));    // or q.emplace(0, 0, k, 0);
        visited[0][0][k] = true;
        while(!q.empty())
        {
            Node cur = q.front();
            q.pop();
            if(cur.x == m-1 && cur.y == n-1)
            {
                return cur.dist;
            }

            for(int i = 0; i < 4; i++)
            {
                int x = cur.x + dx[i];
                int y = cur.y + dy[i];
                if(x >= 0 && x < m && y >= 0 && y < n)
                {
                    if(grid[x][y] == 0 && !visited[x][y][cur.rest])
                    {
                        q.emplace(x, y, cur.rest, cur.dist+1);
                        //or Node next(x, y, cur.rest, cur.dist+1);
                        //q.push(next);  
                        visited[x][y][cur.rest] = true;
                    }
                    else if(grid[x][y] == 1 && cur.rest > 0 
                    			&& !visited[x][y][cur.rest-1])
                    {
                        q.emplace(x, y, cur.rest-1, cur.dist+1);
                        visited[x][y][cur.rest-1] = true;
                    }
                }
            }
        }
        return -1;
    }
};

参考了题解:
https://leetcode-cn.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/solution/wang-ge-zhong-de-zui-duan-lu-jing-by-leetcode/
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值