Given an array of integers where each element represents the max number of steps that can be made forward from that element. Find the minimum number of jumps to reach the end of the array (starting from the first element). If an element is 0, then you cannot move through that element.
Example 1:
Input:
N=11 arr=1 3 5 8 9 2 6 7 6 8 9
Output:
3
Explanation:
First jump from 1st element to 2nd element with value 3. Now, from here we jump to 5th element with value 9, and from here we will jump to last.
My Solution -
// { Driver Code Starts
#include<bits/stdc++.h>
using namespace std;
// } Driver Code Ends
// Function to return minimum number of jumps to end of array
int countJumps(int arr[], int i, int n, int dp[]){
if(i>=n-1)
return 0;
if(dp[i]!=-2)
return dp[i];
if(arr[i]==0)
return -1;
if(arr[i]>=n)
return 1;
int mn = INT_MAX, flag = 0;
for(int j = 1; j<=arr[i]; j++){
if(i+j>n-1)
return 1;
int temp = countJumps(arr,i+j,n,dp);
if(temp==0){
dp[i] = 1;
return dp[i];
}
if(temp==-1){
continue;
}
flag = 1;
mn = min(mn,temp);
}
if(flag == 0){
return -1;
}
dp[i] = 1+mn;
return dp[i];
}
int minJumps(int arr[], int n){
// Your code here
if(arr[0]==0)
return -1;
int dp[n];
for(int i = 0; i<n; i++){
dp[i] = -2;
}
return countJumps(arr,0,n,dp);
}
// { Driver Code Starts.
int main()
{
int t;
cin>>t;
while(t--)
{
int n,i,j;
cin>>n;
int arr[n];
for(int i=0; i<n; i++)
cin>>arr[i];
cout<<minJumps(arr, n)<<endl;
}
return 0;
}
// } Driver Code Ends