如何使用Java实现Frog Jump?

时间:2016-11-29 21:11:52

标签: java algorithm

我遇到了一个名为Frog Jump的问题:

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.

注意:

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.

我只想澄清所问的内容并自行实施。

青蛙一次只能跳1个单位(next jump must be either k - 1, k, or k + 1 units)吗?为什么青蛙在示例1中跳过多个单位,为什么跳过第五块石头?

在示例2中,它表示它返回false,因为there is no way to jump to the last stone as the gap between the 5th and 6th stone is too large,它只相隔4个单位(从4到8),但是青蛙怎么能从第6到第7跳多少个单位例1中的石头?

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

在第一个例子中,他决定跳过第五块石头,因为他的下一次跳跃(长度2)不能让他到达后续的石头(超过那个4) 。另一方面,如果他直接进入第六块石头(3的跳跃),则4的后续跳跃是允许的。

在第二个例子中,你需要能够从第五块石头中至少跳过4,但是你不能以超过2的跳跃落在它上面。因此,这是不可能的。

以与物理学中的动量相同的方式来考虑这一点,它可能会更有意义。

相关问题