LeetCode45. Jump Game II

来源:互联网 发布:mpi编程是什么意思 编辑:程序博客网 时间:2024/06/05 08:14

题目

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.

题目分析

题目意思是给定一个数组,假定现在的位置在下标0,数组的每个元素代表在这个下标的位置最多能跳的步数,目标是找出跳到终点所需的最少步数,假设给出的数组总能跳到终点。
由题目意思是能不跳固定的步数,而是能跳到中途的然后在中途再跳,我们可以使用bfs的思路,把下标分层,从上一层节点的下标+1开始,到上一层的节点跳一下到达最远的地方
为新的一层,如果新层含有终点则直接结束

C++代码

 int jump(int A[], int n) { if(n<2)return 0; int level=0,currentMax=0,i=0,nextMax=0; while(currentMax-i+1>0){//nodes count of current level>0 level++; for(;i<=currentMax;i++){//traverse current level , and update the max reach of next levelnextMax=max(nextMax,A[i]+i);if(nextMax>=n-1)return level;   // if last element is in level+1,  then the min jump=level  } currentMax=nextMax; } return 0; }