forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
34 lines (32 loc) · 864 Bytes
/
Solution.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
class Solution {
private Boolean[][] f;
private Map<Integer, Integer> pos = new HashMap<>();
private int[] stones;
private int n;
public boolean canCross(int[] stones) {
n = stones.length;
f = new Boolean[n][n];
this.stones = stones;
for (int i = 0; i < n; ++i) {
pos.put(stones[i], i);
}
return dfs(0, 0);
}
private boolean dfs(int i, int k) {
if (i == n - 1) {
return true;
}
if (f[i][k] != null) {
return f[i][k];
}
for (int j = k - 1; j <= k + 1; ++j) {
if (j > 0) {
int h = stones[i] + j;
if (pos.containsKey(h) && dfs(pos.get(h), j)) {
return f[i][k] = true;
}
}
}
return f[i][k] = false;
}
}