Jump Game II一道优化bfs题

来源:互联网 发布:淘宝外宣兼职违法吗 编辑:程序博客网 时间:2024/06/05 14:29

题目描述:
Given an array of non-negative integers, you are initially positioned at the first index of the array.

Each element in the array represents your maximum jump length at that position.

Your goal is to reach the last index in the minimum number of jumps.

For example:
Given array A = [2,3,1,1,4]

The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.)

Note:
You can assume that you can always reach the last index.

分析:
考虑到如果在儿子时已经到了孙子没法达到的点,那么这个孙子节点没有必要加入队列。

代码如下:

    struct mypair{        int x;        int y;    };int jump(vector<int>& nums) {if(nums.size()==1) return 0;        queue<mypair>temp;        vector<int>a;    a.push_back(0);        mypair k;        k.x=0;        k.y=0;        temp.push(k);        while(!temp.empty()){            mypair s=temp.front();            temp.pop();            if(s.y+nums[s.y]>=nums.size()-1) return s.x+1;            while(a.size()<=s.x+1) a.push_back(0);            int p=nums[s.y];            while(p>0){                k.x=s.x+1;                k.y=p+s.y;                if(k.y<=a[s.x]) break;//扔掉没意义的节点                if(k.y>a[s.x+1]) a[s.x+1]=k.y;                 temp.push(k);                p--;            }        }}
原创粉丝点击