leetcode--403--frog jump

来源:互联网 发布:c语言多线程 编辑:程序博客网 时间:2024/06/03 15:42

转载请注明出处:

http://write.blog.csdn.net/postedit/77619362



问题:

https://leetcode.com/problems/frog-jump/description/


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.

Example 2:

 

[0,1,2,3,4,8,9,11]

 

Return false. There is no way to jump to the last stone as

the gap between the 5th and 6th stone is too large.


参考答案: C++ 

https://discuss.leetcode.com/topic/71908/java-dfs-17ms-beat-99-28-so-far

 

unordered_set<int> set;    bool dfs(int k, int pos, int destination)    {        if(pos > destination || set.find(pos) == set.end()) return false;        if(pos == destination) return true;        for(int i = 1; i >= -1; i--)            if(k+i > 0 && dfs(k+i, pos+k+i, destination)) return true;        return false;    }    bool canCross(vector<int>& stones) {        int n = stones.size();        if(n <= 1) return true;        set.insert(0);        for(int i = 1; i < n; i++)        {            set.insert(stones[i]);            if(stones[i] - stones[i-1] > i) return false;//key point !!        }        return dfs(1, 1, stones[n-1]);}


思路:


答案的思路不难理解,通过DFS来解决问题。需要关注的几个点:


1. 在将数据放入 set 集合时,做了预判断,如果相邻两个石头的距离大于最大跳跃步数,则直接返回失败,


这里,第 0  块最大跳跃步是 1,第 1  块最大跳跃步是 2... 第 n  可能的最大跳跃步是 n+1


这一处理步骤直接 pass 很多用例,而且将距离直接存储起来,以后不需要再读取数组,大大提升了效率

 

2. dfs 函数中 为上次的跳跃数,pos 是当前位置坐标,上次的跳跃数 是 dfs 的关键。


dfs处理过程中,每次推进都有三种情况,即跳跃步数为 k-1和 k +1


成功的条件只有1个:

       当前位置是目标位置


失败的条件有3个:

       1)当前位置超出目标位置


       2)set  集合中不存在位于 pos 的石头,这种情况,实际上,青蛙跳到了水中


       3)dfs 遍历结束,仍无法找到满足的跳跃方式

原创粉丝点击