|
C语言趣味程序百例精解之java实现(93)汉内塔
程序:
public class Test93{
public static void main(String args[]){
runHanoi(4,'A','B','C');
}
public static void runHanoi(int n,char x,char y,char z){
if(n==1){
System.out.println("Move top disk from peg "+x+" to peg "+z);
}else{
runHanoi(n-1,x,z,y);
runHanoi(1,x,y,z);
runHanoi(n-1,y,x,z);
}
}
}
求解4个盘的输出是:
Move top disk from peg A to peg B
Move top disk from peg A to peg C
Move top disk from peg B to peg C
Move top disk from peg A to peg B
Move top disk from peg C to peg A
Move top disk from peg C to peg B
Move top disk from peg A to peg B
Move top disk from peg A to peg C
Move top disk from peg B to peg C
Move top disk from peg B to peg A
Move top disk from peg C to peg A
Move top disk from peg B to peg C
Move top disk from peg A to peg B
Move top disk from peg A to peg C
Move top disk from peg B to peg C |
|