forked from fineanmol/Hacktoberfest2024
-
Notifications
You must be signed in to change notification settings - Fork 30
/
frogJump.cpp
44 lines (38 loc) · 955 Bytes
/
frogJump.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// C++ program to find Minimum
// number of jumps to reach end
#include <bits/stdc++.h>
using namespace std;
// Function to return the minimum number
// of jumps to reach arr[h] from arr[l]
int minJumps(int arr[], int n)
{
// Base case: when source and
// destination are same
if (n == 1)
return 0;
// Traverse through all the points
// reachable from arr[l]
// Recursively, get the minimum number
// of jumps needed to reach arr[h] from
// these reachable points
int res = INT_MAX;
for (int i = n - 2; i >= 0; i--) {
if (i + arr[i] >= n - 1) {
int sub_res = minJumps(arr, i + 1);
if (sub_res != INT_MAX)
res = min(res, sub_res + 1);
}
}
return res;
}
// Driver Code
int main()
{
int arr[] = { 1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Minimum number of jumps to";
cout << " reach the end is " << minJumps(arr, n);
return 0;
}
// This code is contributed
// by Shivi_Aggarwal