跳步游戏

题目:

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

分析:每跳一步记录下此步能跳的最远位置,若最远位置超过了数组长度,循环结束,否则继续跳步。

代码如下:

int jump(int A[], int n) {
        if(n<=1)return 0;
        int position = 0,step=0,i=0;
        while(i<n&&i<=position)
        {
            int tmp=position;
            while(i<=tmp)
            {
                if(i+A[i]>position)position=i+A[i];
                i++;
            }
            step++;
            if(position>=n-1) return step;
        }
        return -1;
    }

原文地址:https://www.cnblogs.com/javawebsoa/p/3045631.html