forked from klw910/cracking-the-coding-interview
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMinimum number of jumps to reach end
58 lines (50 loc) · 1.68 KB
/
Minimum number of jumps to reach end
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
int minJumps(int arr[], int n)
{
int *jumps = new int[n]; // jumps[0] will hold the result
int min;
// Minimum number of jumps needed to reach last element
// from last elements itself is always 0
jumps[n-1] = 0;
int i, j;
// Start from the second element, move from right to left
// and construct the jumps[] array where jumps[i] represents
// minimum number of jumps needed to reach arr[m-1] from arr[i]
for (i = n-2; i >=0; i--)
{
// If arr[i] is 0 then arr[n-1] can't be reached from here
if (arr[i] == 0)
jumps[i] = INT_MAX;
// If we can direcly reach to the end point from here then
// jumps[i] is 1
else if (arr[i] >= n - i - 1)
jumps[i] = 1;
// Otherwise, to find out the minimum number of jumps needed
// to reach arr[n-1], check all the points reachable from here
// and jumps[] value for those points
else
{
min = INT_MAX; // initialize min value
// following loop checks with all reachable points and
// takes the minimum
for (j = i+1; j < n && j <= arr[i] + i; j++)
{
if (min > jumps[j])
min = jumps[j];
}
// Handle overflow
if (min != INT_MAX)
jumps[i] = min + 1;
else
jumps[i] = min; // or INT_MAX
}
}
return jumps[0];
}
// Driver program to test above function
int main()
{
int arr[] = {1, 3, 6, 1, 0, 9};
int size = sizeof(arr)/sizeof(int);
printf("Minimum number of jumps to reach end is %d ", minJumps(arr,size));
return 0;
}