# C Program for Minimum number of jumps to reach the end

CServer Side ProgrammingProgramming

We are given, an array of non-negative integers denoting the maximum number of steps that can be made forward from that element. The pointer is initially positioned at the first index [0 index] of the array. Your goal is to reach the last index of the array in the minimum number of steps. If it is not possible to reach the end of the array then print the maximum integer.

naive approach is to begin from initial{the primary} component and recursively call for all the components accessible from the first element. The minimum range of jumps to reach the end from first is calculated using the minimum range of jumps required to achieve end from the elements accessible from first.

minJumps(start, end) = Min ( minJumps(k, end) )
for all k accessible from the start

Here we’ll use the top-down approach of dynamic programming. We’ll use Hashmap to store the subproblem results and whenever we create a solution, first check if the subproblem is already resolved, if yes then use it.

Input: { 1, 2, 4, 1, 2, 2, 1, 1, 3, 8 }
Output: Minimum number of steps = 6 {1-->2-->4-->1-->3-->8}

## Explanation

The first element is 1, so it can only go to 2. The second element is 2, so can make at most 2 steps eg to 4 or 1. It goes to 4 from where it reaches 1 and so on.

The complexity of dynamic programming approach to find the minimum number of jumps to reach the end of an array is O(n^2) with space complexity of O(n)

## Example

Live Demo

#include<stdio.h>
#include<limits.h>
int min_steps (int arr[], int n){
int steps[n];
int i, j;
if (n == 0 || arr == 0)
return INT_MAX;
steps = 0;
for (i = 1; i < n; i++){
steps[i] = INT_MAX;
for (j = 0; j < i; j++){
if (i <= j + arr[j] && steps[j] != INT_MAX){
steps[i] = (steps[i] < (steps[j] + 1)) ? steps[i] : steps[j] + 1;
break;
}
}
}
return steps[n - 1];
}
int main (){
int arr;
int n;
printf ("Enter size of the array:");
scanf ("%d", &n);
printf ("Enter elements in the array:");
for (int i = 0; i < n; i++){
scanf ("%d", &arr[i]);
}
printf ("Minimum number of steps : %d", min_steps (arr, n));
return 0;
}

## Output

Enter size of array : 7
Enter elements in the array :2 1 1 5 2 1 1
Minimum number of steps : 3