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.)

解法:

利用层次遍历,bfs算法,把第i+1层定义为第i层可以达到的最远位置内的点,2|3,1|1,4  则需要两次

2 第一层,

3,1 第二层

1,4 第3层  从第一层跳到第3层,需要2步


代码

int jump(vector<int>& nums) {

        int size=nums.size();

        if(size<2)

            return 0;

        

        int level=0,curmaxreach=0,nextmaxreach=0;

        int pos=0;

        while(curmaxreach-pos+1>0){//每层节点数,如果该层节点数为0,说明由上一层以及无法进入下一层,结束,可以返回MAX_INT

            level++;

            for(;pos<=curmaxreach;++pos){//必须含有=

                nextmaxreach=max(nextmaxreach,nums[pos]+pos);

                if(nextmaxreach>=size-1)

                    return level;

            }

            curmaxreach=nextmaxreach;

        }

        

        return numeric_limits<int>::max();

    }