1. 程式人生 > >The minimum number of elements to reach the end of an array

The minimum number of elements to reach the end of an array

Given an array of integers, each element represents the max number of jumps that you can move forward.
Write a piece of code to find out the minimum number of elements you need to select to reach the end of the array (starting from the first element).
• All integers is equal to or greater than 0
• If an element is 0, you cannot make any jumps
• -1 should be output if it is unable to reach the end of the array
Here is an example to illustrate the question.
Sample Input: 1,3,5,2,9,3,1,1,8
Sample Output: 3
Explanation:
Here the min # of selections is : 3
with the sequence : 1-> 3 -> 9 ->8
First element is 1, so can only go to 3.

Second element is 3, so can make at most 3 jumps: eg to 5 or 2 or 9.

Another example:
Input: 1, 0
Ouput: -1
Explanation: the first element is 1, so can only go to 0. Then can not make any jumps, so we can not reach the end of the array.

#include <iostream>
using namespace std;

int walk(int *arr, int len);

int walk(int *arr, int len)
{
	if (len <=0)
	{
		return 0;
	}
	if(*arr <= 0)
	{	
		return -1;
	}
	//print the element indicating the max steps we can take
	cout<<*arr<<" ";
	//we can reach the end of array by this element
	if(len == 1 || *arr > len-1)
	{
		return 1;
	}
	int max_step = *arr;
	//this array has at least two elements
	//we suppose the nearest element can proceed further
	int *pos = arr+1;
	int *p;
	for (p = arr+2; p<=arr+max_step; p++)
	{
		//if the next element can proceed further, then mark the position.
		if (*p > *pos-(p-pos))
		{
			pos = p;
		}
	}
	int steps = walk(pos, len-(pos-arr));
	if (steps == -1)
	{
		return -1;//we can never reach the end
	}
	else
	{
		return 1+steps;//increment the steps
	}
}


int main()
{
	int arr[] = {1,3,5,2,4,3,1,2,0,0};
	int steps = walk(arr, sizeof(arr)/sizeof(int));
	cout<<endl<<"the steps:"<<steps<<endl;
	return 0;
}