
class Solution {
public boolean canCross(int[] stones) {
// 回溯法递归
int n = stones.length;
Map<Integer, Boolean> map = new HashMap<>();
return DFS(stones, 0, 0, n, map);
}
/**
* index: 表示现在所处的索引
* k: 表示上一步跳跃了几个单元格
* n: 表示数组长度
* map: 表示经历过的状态
**/
private boolean DFS(int[] stones, int index, int k, int n, Map<Integer, Boolean> map) {
// 递归终止条件
// System.out.println("index:" + index + " k:" + k);
if (index == n - 1) {
return true;
}
int key = index * 1000 + k;
if (map.containsKey(key)) {
return false;
} else {
map.put(key, true);
}
for (int i = index + 1; i < n; i++) {
int gap = stones[i] - stones[index];
if (k - 1 <= gap && gap <= k + 1) {
if (DFS(stones, i, gap, n, map)) {
return true;
}
} else if (gap > k + 1) {
break;
} else {
continue;
}
}
return false;
}
}