动态规划 解 青蛙跳石过河

题目描述:

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.
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.
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.

        本题的意思是青蛙正在通过一条河,而河被切分成了X个单元,每个单元包含若干个单位单元,每个单元内不存在可以跳跃的石头。但是,青蛙可以
        在单元的石头上跳跃,不能淌水。如果青蛙前一次跳跃了K个单位单元,那么下一次跳跃只能跳K-1,K,K+1个单位单元(当然青蛙为了过河,只能向前跳 跃)。给出一序列的石头的位置,是以单元递增的形式存在的(每个值代表相距开始的距离)。我们来判断青蛙是否可以通过这条河。初始状态的情况下, 青蛙是在第一块石头上,假设第一次跳跃是1单元。
  如下面的输入:
  Unit    0    1    2    3    4    8    9    11
                  Position        1    2    3    4    5    6    7     8
  就是说明       0代表原地;1代表第一块石头距原地的距离;2代表第二块石头距原地的距离,则很显然第二块石头距第一块1个单元。 ......
                  如此,我们可以知道,这只青蛙跳不过去:因为在第4和第5位置间跳了4-3=1个单元,而根据K-1,K,K+1,不可能在第5和第6位置间达到8-4=4个单元。
解题:
 for(i=0;i<length;i++)
{
知道跳至i的,i之前的一个位置j;//因为可能一下子跳了多个单元空隙,因此不一定j=i-1;
gap=pos[i]-pos[j];//找到跳跃之间的空隙有多大,即刚从j跳到i的空隙;
使pos=(pos[i]+gap-1 || pos[i]+gap || pos[i]+gap+1),遍历i后面的位置,看是否可以有pos==pos[j],length>j>=i+1;
如果有,则将j作为新的位置,并且记录下来i是其前一点,此次的跳跃幅度是pos[j]=pos[i];继续向下一个点前进;
如果没有,则很明显不能过河;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值