leetcode 最少跳跃次数(BFS,剪枝)

题目大意:

已知an,从i出发的话,每次我们可以选择走去min(n,i + a[i]),或者[0,i-1],现在问我们最少几步可以走到n.

n<=1e6

解题思路:

无权最短路,优先考虑BFS,但是我们每次假如按照题意每次都往前走的话会超时复杂度n^2,那么我们可以怎么改进呢?我们发现,从i位置出发,下次走的时候枚举的起点不必要从0开始到i-1,假如之前我们已经在u点往前跳过了,那么我们应该从之前跳过的那一段的位置(即u+1)开始到i-1。这样子枚举即可。

const int inf = 1e9;
class Solution {
public:
    int minJump(vector<int>& jump) {
        int n = jump.size();
        vector<int> dist(n+1,0);
        int ls = 0;
        vector<int> flag(n+1,0);
        queue<int> q;
        q.push(0);
        flag[0] = 1;
        while(!q.empty()){
            int u = q.front();q.pop();
            if(u == n)break;
            for(int nx=ls;nx<u;nx++){
                if(!flag[nx]){
                    flag[nx] = 1;
                    dist[nx] = dist[u] + 1;
                    q.push(nx);
                }
            }
            ls = max(ls, u+1);
            int nx = min(n,u + jump[u]);
            if(!flag[nx]){
                    flag[nx] = 1;
                    dist[nx] = dist[u] + 1;
                    q.push(nx);
            }
        }
        return dist[n];
        
    }
};

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值