Skip to content

Commit 41b623e

Browse files
committed
Add 'Jump Game II' solution.
1 parent a6e4fee commit 41b623e

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

Jump_Game_II.cpp

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/*
2+
Given an array of non-negative integers, you are initially positioned at the
3+
first index of the array.
4+
Each element in the array represents your maximum jump length at that
5+
position.
6+
Your goal is to reach the last index in the minimum number of jumps.
7+
8+
For example:
9+
Given array A = [2,3,1,1,4]
10+
The minimum number of jumps to reach the last index is 2.
11+
(Jump 1 step from index 0 to 1, then 3 steps to the last index.)
12+
*/
13+
14+
class Solution {
15+
public:
16+
int jump(int A[], int n) {
17+
if (n <= 1) return 0;
18+
19+
queue<int> q; // for BFS
20+
vector<int> cnt(n, 0); // c[i] represents the minimal jumps from 0 to i
21+
q.push(0);
22+
while (!q.empty()) {
23+
int start = q.front();
24+
if (start + A[start] >= n - 1) return cnt[start] + 1;
25+
for (int i=A[start]; i>0; i--) {
26+
if (cnt[start+i] == 0) {
27+
cnt[start+i] = cnt[start] + 1;
28+
q.push(start+i);
29+
} else {
30+
// if i has been reached, then i-1 must has been reached too.
31+
// So just skim others.
32+
// This makes sure that every position will be pushed once, be
33+
// popped once and visit at most one unchanged position.
34+
break;
35+
}
36+
}
37+
q.pop();
38+
}
39+
40+
return -1;
41+
}
42+
};

0 commit comments

Comments
 (0)