forked from algorithm009-class01/algorithm009-class01
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCanAcross.java
More file actions
33 lines (29 loc) · 1004 Bytes
/
CanAcross.java
File metadata and controls
33 lines (29 loc) · 1004 Bytes
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
package dynamic;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
public class CanAcross {
public boolean canCross(int[] stones){
HashMap<Integer, Set<Integer>> map = new HashMap<>();
for (int i = 0; i < stones.length; i++) {
map.put(stones[i],new HashSet<Integer>());
}
map.get(0).add(0);
for (int i = 0; i < stones.length; i++) {
for (int k : map.get(stones[i])){
for (int step = k-1;step<=k+1;step++){
if (step >0 && map.containsKey(stones[i] + step)){
map.get(stones[i] + step).add(step);
}
}
}
}
return map.get(stones[stones.length -1]).size() > 0;
}
public static void main(String[] args) {
int[] stones = {0,1,3,5,6,8,12,17};
CanAcross canAcross = new CanAcross();
boolean r = canAcross.canCross(stones);
System.out.println(r);
}
}