动态规划 解 青蛙跳石过河

来源:互联网 发布:时间 知乎 编辑:程序博客网 时间:2024/04/28 03:35

题目描述:

A frog is crossing a river. The river is divided intox 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 wask units, then its next jump must be eitherk 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