java青蛙_趣味算法——青蛙过河(JAVA)

/*** 青蛙过河

*@authorrubekid

**/

public classRiverFrog {public static final int LEFT_FROG = -1;public static final int RIGHT_FROG = 1;public static final int STONE = 0;private int[] frogs;private intzeroIndex;private intlength;private int step = 0;public RiverFrog(intnumber) {

frogs= new int[number * 2 +1];

length=frogs.length;

zeroIndex= length /2;for(int i=0; i< number; i++){

frogs[i]=LEFT_FROG;

}

frogs[zeroIndex]=STONE;for(int i=0; i< number; i++){

frogs[i+ zeroIndex + 1] =RIGHT_FROG;

}

}public voidrun(){while(!isMoveEnd(LEFT_FROG) || !isMoveEnd(RIGHT_FROG)){int left = zeroIndex - 1;int right = zeroIndex+1;if(left>-1 && right 0 && frogs[left-1] == RIGHT_FROG){//若移动right,则在中间有两只RIGHT并排

this.move(right);

}else{this.move(left);

}

}else if(left > 0 && frogs[left-1]==LEFT_FROG ){this.move(left-1);

}else if(right <= length && frogs[right+1] ==RIGHT_FROG){this.move(right+1);

}

}else{if(frogs[left] ==RIGHT_FROG){if(left > 0 && frogs[left-1] ==LEFT_FROG){this.move(left - 1);

}else if(right+1 < length && frogs[right+1] ==RIGHT_FROG){this.move(right+1);

}else if(frogs[right] ==RIGHT_FROG){this.move(right);

}

}else if(frogs[right] ==LEFT_FROG){if(right+1 < length && frogs[right+1] ==RIGHT_FROG){this.move(right + 1);

}else if(left >0 && frogs[left-1] ==LEFT_FROG){this.move(left-1);

}else if(frogs[left] ==LEFT_FROG){this.move(left);

}

}

}

}else if(left == -1){if(frogs[right] == LEFT_FROG && right

}else{this.move(right);

}

}else if(right ==length){if(frogs[left] == RIGHT_FROG && left > 0){this.move(left-1);

}else{this.move(left);

}

}

}

System.out.println("step:" +step);

}private void move(inti){int temp =frogs[i];

frogs[i]=frogs[zeroIndex];

frogs[zeroIndex]=temp;

zeroIndex=i;

step++;

print();

}private boolean isMoveEnd(intvalue){int i=0; int max=zeroIndex;if(value ==LEFT_FROG){

i= zeroIndex+1;

max=length;

}for(int j=i; j

}

}return true;

}private voidprint(){

StringBuffer stringBuffer= newStringBuffer();for(intfrog : frogs){if(frog>-1){

stringBuffer.append(" " +frog + " ");

}else{

stringBuffer.append(frog+ " ");

}

}

System.out.println(stringBuffer.toString());

}

}

你可能感兴趣的:(java青蛙)