# Minimum Number of Jumps Problem – Dynamic Programming Solutions

«
»

This is a C++ Program that Solves Minimum Number of Jumps Problem using Dynamic Programming technique.

Problem Description

Given an array of integers where each element represents the max number of steps that can be made forward from that element. Write a program to find the minimum number of jumps to reach the end of the array (starting from the first element). If an element is 0, then cannot move through that element.

Problem Solution

We will progressively calculate the minimum number of jumps required to reach at sttep 1, then at step 2 and finally to reach end. Everytime when we calculate the minimum no. of jumps value for a step, we will use this value to calculate the desired value for further steps.

Expected Input and Output

Case-1:

```
jump values=2 8 3 6 9 3 0 0 1 3

Minimum number of jumps required to reach end is 2 (2->8->3)```
Program/Source Code

Here is source code of the C++ Program to Solve Minimum Number of Jumps Problem. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
1. `#include<iostream>`
2. `#include<climits>`
3. `using namespace std;`
4. ` `
5. `int minJumps(int n, int jumps[])`
6. `{`
7. `    int i, j;`
8. `    int dp[n];`
9. `    dp[0]=0;`
10. ` `
11. `    //initialize with infinity`
12. `    for(i=1;i<n;i++)`
13. `        dp[i]=INT_MAX;`
14. ` `
15. `    for(i=0;i<n-1;i++)`
16. `    {`
17. `        for(j=1;j<=jumps[i] && i+j<n;j++)`
18. `        {`
19. `            dp[i+j]=min(dp[i+j],1+dp[i]);`
20. `        }`
21. `    }`
22. ` `
23. `    return dp[n-1];`
24. `}`
25. ` `
26. `int main()`
27. `{`
28. `    int i,j;`
29. `    int n;`
30. ` `
31. `    cout<<"Enter the total number of steps"<<endl;`
32. `    cin>>n;`
33. ` `
34. `    int jumps[n];`
35. ` `
36. `    cout<<"Enter the max jump values for each step"<<endl;`
37. `    for(i=0;i<n;i++)`
38. `        cin>>jumps[i];`
39. ` `
40. `    cout<<"Minimum number of jumps required to reach end is "<<endl;`
41. `    cout<<minJumps(n, jumps);`
42. ` `
43. `    cout<<endl;`
44. `    return 0;`
45. `}`
Program Explanation

In the main function, we ask the user to input for the number of steps and the jump values for each step. We pass this value to the function minJumps as parameter. This function will calculate the expected result and return it. The returned value will be displayed.

Runtime Test Cases
```
Case-1:
\$ g++ min_jumps.cpp
\$ ./a.out
Enter the total number of steps
10
Enter the max jump values for each step
2 8 3 6 9 3 0 0 1 3
Minimum number of jumps required to reach end is
2```

Sanfoundry Global Education & Learning Series – Dynamic Programming Problems.
To practice all Dynamic Programming Problems, here is complete set of 100+ Problems and Solutions.