題目描述:
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--;
}
}
}