JAVA-汉诺塔问题(hanoi)
import java.util.Scanner;
public class Hanoi_1 {
int sum = 0;
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("Enter numbers of disks : ");
int n = sc.nextInt();
Hanoi_1 Han = new Hanoi_1();
char A='A',B='B',C='C';
Han.Hanoi(n,A,B,C);
System.out.println("最终移动次数:"+Han.sum);
}
void move(char A,int n,char C){
sum++;
System.out.println("第"+sum+"次移动"+" move disk"+n+" from "+A+" to "+C);
}
void Hanoi(int n,char A,char B,char C) {
if(n == 1)move(A,1,C);
else{
Hanoi(n-1,A,C,B); //将A上标号为1至n-1的圆盘移到B,C做辅助塔
move(A,n,C); //将编号为n的圆盘从A移到C
Hanoi(n-1,B,A,C);
}
}
}
|