-
Notifications
You must be signed in to change notification settings - Fork 114
/
Jump1.java
69 lines (61 loc) · 2.09 KB
/
Jump1.java
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
59
60
61
62
63
64
65
66
67
68
69
/*
* Given an array of non-negative integers, you are initially positioned at the first index of the array.
*
Each element in the array represents your maximum jump length at that position.
Determine if you are able to reach the last index.
For example:
A = [2,3,1,1,4], return 1 ( true ).
A = [3,2,1,0,4], return 0 ( false ).
Return 0/1 for this problem
http://n00tc0d3r.blogspot.com/2013/03/jump-game.html
*/
import java.util.*;
public class Jump1{
public static int canJump(ArrayList<Integer> a) {
if(a == null || a.size() == 0)
return 0;
if(a.size() == 1)
return 1;
int result = 0;
int[] canReach = new int[a.size()];
for(int i = a.size() -2, dist = 1; i >= 0; i--, dist++){
System.out.println("For i : " + i + " dist : " + dist);
if(a.get(i) >= dist){
System.out.println("\t a.get(i) : " + a.get(i) + " >= " +dist);
canReach[i] = 1;
}
else{
int j = 1;
while(j <= a.get(i) && canReach[i+j] != 1){
System.out.println("\t checking in jump range");
++j;
}
if(j <= a.get(i))
canReach[i] = 1;
}
}
for(int i =0; i < a.size(); i++)
System.out.print(canReach[i] + " ");
System.out.println();
return canReach[0];
}
public static int canJumpDP(ArrayList<Integer> a) {
int next = a.size() - 1;
for(int i = a.size() - 2; i >= 0; i--){
System.out.println("Next : " + next + " i : " + i);
System.out.println("Check if a.get(i) " + a.get(i) + " >= " + (next - i) );
if(a.get(i) >= next - i)
next = i;
}
return next == 0 ? 1 : 0;
}
public static void main(String[] args){
ArrayList<Integer> a = new ArrayList<Integer>();
a.add(2);
a.add(3);
a.add(1);
a.add(1);
a.add(4);
System.out.println(canJumpDP(a));
}
}