java青蛙终点_一个青蛙过河程序及其解析

package test;

import java.util.Arrays;

/**

*

* @author Yovn

*

*/

public class FrogJump {

private int steps[];

private int states[];

private static class Step

{

int offset=-1;

int jump;

int jumpTo;

}

private Step jumps[];

private int initS;

public FrogJump()

{

steps=new int[81*27];

states=new int[7];

for(int i=0;i<3;i++)states[i]=1;

for(int i=4;i<7;i++)states[i]=2;

Arrays.fill(steps, -1);

steps[0]=0;

jumps=new Step[81*27];

initS=makeS();

}

public int shortestSteps(int s)

{

if(steps[s]==-1)

{

int minStep=Integer.MAX_VALUE;

Step oneStep=new Step();

for(int i=0;i<7;i++)

{

if(states[i]==1)

{

if(i>4)

{

states[i]=0;

minStep = recurFind(minStep,oneStep,i,7-i);

states[i]=1;

}

else

{

if(states[i+1]==0)

{

states[i]=0;

states[i+1]=1;

minStep = recurFind(minStep,oneStep,i,1);

states[i]=1;

states[i+1]=0;

}

if(states[i+2]==0)

{

states[i]=0;

states[i+2]=1;

minStep = recurFind(minStep,oneStep,i,2);

states[i]=1;

states[i+2]=0;

}

}

}

else if(states[i]==2)

{

if(i<2)

{

states[i]=0;

minStep = recurFind(minStep,oneStep,i,-1-i);

states[i]=2;

}

else

{

if(states[i-1]==0)

{

states[i]=0;

states[i-1]=2;

minStep = recurFind(minStep,oneStep,i,-1);

states[i]=2;

states[i-1]=0;

}

if(states[i-2]==0)

{

states[i]=0;

states[i-2]=2;

minStep = recurFind(minStep,oneStep,i,-2);

states[i]=2;

states[i-2]=0;

}

}

}

}

steps[s]=minStep;

jumps[s]=oneStep;

}

return steps[s];

}

private final int recurFind(int minStep, Step oneStep, int pos, int jump) {

int toS=makeS();

int r=shortestSteps(toS);

if(r

{

oneStep.jump=jump;

oneStep.offset=pos;

oneStep.jumpTo=toS;

minStep=r+1;

}

return minStep;

}

public void printPath()

{

int s=initS;

int i=1;

while(s!=0)

{

System.out.println("["+(i++)+"] Frog at #"+jumps[s].offset+" jumps #"+jumps[s].jump);

s=jumps[s].jumpTo;

}

}

private final int makeS() {

int r=0;

int p=1;

for(int i=0;i<7;i++)

{

r+=p*states[i];

p*=3;

}

return r;

}

/**

* @param args

*/

public static void main(String[] args) {

FrogJump fj=new FrogJump();

int steps=fj.shortestSteps(fj.initS);

System.out.println("use "+steps+" steps!");

fj.printPath();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值