A frog is crossing a river. The river is divided into x units and at each unit there may or may not exist a stone. The frog can jump on a stone, but it must not jump into the water.
Given a list of stones’ positions (in units) in sorted ascending order, determine if the frog is able to cross the river by landing on the last stone. Initially, the frog is on the first stone and assume the first jump must be 1 unit.
If the frog’s last jump was k units, then its next jump must be either k - 1, k, or k + 1 units. Note that the frog can only jump in the forward direction.
Note:
The number of stones is ≥ 2 and is < 1,100.
Each stone’s position will be a non-negative integer < 231.
The first stone’s position is always 0.
Example 1:
[0,1,3,5,6,8,12,17]
There are a total of 8 stones.
The first stone at the 0th unit, second stone at the 1st unit,
third stone at the 3rd unit, and so on…
The last stone at the 17th unit.
Return true. The frog can jump to the last stone by jumping
1 unit to the 2nd stone, then 2 units to the 3rd stone, then
2 units to the 4th stone, then 3 units to the 6th stone,
4 units to the 7th stone, and 5 units to the 8th stone.
给出一个数组,表示石头的位置,青蛙在跳了k步之后,下一步只能跳k-1, k, 或者k+1步,当然可以隔着石头跳,只要能到达,问是否能到达最后一个位置。
思路:
从0位置开始,因为只能往前跳,对0而言,-1后退是不行的,0原地踏步也不行,第一次只能跳k=1步,到下一个。然后在下一个位置跳k-1, k, 或k+1步,重复迭代,直到到达终点或者掉进水里(位置不是数组中的元素)为止。
DFS
因为下一次跳多少步是由上一次的步数k决定的,所以需要当前位置 和 上一次跳了多少步才到了这个位置 这两个信息(pos, jump)。起始点应该是(0, 0)。
那么下一步应该是(pos+jump-1, jump-1), 或者(pos+jump, jump), 或者(pos+jump+1, jump+1)
终止条件
(1) 掉进水里,即位置不在数组内
(2) 相同的pos和jump,以前曾经失败了,就不需要再次探索
(3) 到达终点,成功
关于保存之前失败的pos和jump这一对信息,为了便于搜索,用HashSet。但是这有两个信息,而且一个pos可能对应不同的jump,用一个key-value对不能满足。为了不用map这种结构,用一个字符串保存pos+jump, 保存在HashSet里
class Solution {
int end = 0;
HashSet<Integer> set = new HashSet<>();
HashSet<String> failed = new HashSet<>();
public boolean canCross(int[] stones) {
if(stones == null || stones.length == 0) {
return false;
}
for(int i = 0; i < stones.length; i ++) {
set.add(stones[i]);
}
end = stones[stones.length - 1];
return dfs(0, 0);
}
boolean dfs(int pos, int jump) {
if(pos == end) {
return true;
}
if(!set.contains(pos)) {
return false;
}
if(failed.contains(""+pos+jump)){
return false;
}
if(jump > 1 && dfs(pos+jump-1, jump-1)) {
return true;
}
if(jump > 0 && dfs(pos+jump, jump)) {
return true;
}
if(dfs(pos+jump+1, jump+1)) {
return true;
}
failed.add(""+pos+jump);
return false;
}
}