Skip to content

Commit 2623fed

Browse files
committed
jump game
1 parent 1de836b commit 2623fed

1 file changed

Lines changed: 65 additions & 0 deletions

File tree

PuzzleCoding/src/JumpGame.java

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
/**
2+
* Given an array of non-negative integers,
3+
* you are initially positioned at the first index of the array.
4+
* Each element in the array represents your maximum jump length at that position.
5+
* Your goal is to reach the last index in the minimum number of jumps.
6+
* For example:
7+
* Given array A = [2,3,1,1,4]
8+
* The minimum number of jumps to reach the last index is 2.
9+
* (Jump 1 step from index 0 to 1, then 3 steps to the last index.)
10+
*/
11+
public class JumpGame {
12+
public static void main(String[] args) {
13+
int[] a1 = new int[]{2, 3, 1, 1, 4};
14+
int[] a2 = new int[]{2, 3, 1, 1, 0,4};
15+
16+
jumpGame(a1);
17+
jumpGame(a2);
18+
19+
20+
}
21+
22+
public static void jumpGame(int[] a) {
23+
if (a.length == 0) return;
24+
25+
int[] preStep = new int[a.length];
26+
27+
for (int i = 0; i < preStep.length; i++)
28+
preStep[i] = -1;
29+
30+
boolean reachEnd = false;
31+
int furthest = a[0];
32+
int i = 0;
33+
while (i <= furthest) {
34+
furthest = Math.max(furthest, a[i] + i);
35+
for (int j = 0; j <= furthest; j++) {
36+
if (j < a.length) {
37+
if (preStep[j] == -1)
38+
preStep[j] = i;
39+
else {
40+
if (preStep[j] > i)
41+
preStep[j] = i;
42+
}
43+
}
44+
}
45+
if (furthest >= a.length - 1) {
46+
reachEnd = true;
47+
break;
48+
}
49+
i++;
50+
}
51+
52+
if (!reachEnd) {
53+
System.out.println("unreachable!");
54+
} else {
55+
int end = a.length - 1;
56+
while (end != 0) {
57+
System.out.print(a[end] +"->");
58+
end = preStep[end];
59+
}
60+
System.out.print(a[end]);
61+
System.out.println();
62+
}
63+
64+
}
65+
}

0 commit comments

Comments
 (0)