Hanoi汉罗塔问题

来源:互联网 发布:两个表格数据匹配重复 编辑:程序博客网 时间:2024/06/02 13:13
import java.util.Scanner;

/*
 * 汉罗塔问题
 */
public class HanoiExec {




public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("请输入盘子数n");
Scanner sn=new Scanner(System.in);
int n=sn.nextInt();
HanoiExec hanoi=new HanoiExec();
System.out.println("The steps to move " +n+" disks:");
hanoi.hanoi(n, 'A', 'B', 'C');
System.out.println(n+"个盘子最少需要移动"+(Math.pow(2,n)-1)+"次。");
}

public void hanoi(int n,char one ,char two,char three){
if(n==1){
this.move(one, three);
}else{
//分三步:
//1、借助第三个柱子把第一个柱子的n-1个盘子移动到第二个柱子上
//2、把第一个柱子上的第n个盘子从第一个柱子移动最终的第三个柱子上
//3、借助第一个柱子把第二个柱子的n-1个盘子移动到第三个柱子
this.hanoi(n-1,one,three,two);
this.move(one ,three);
this.hanoi(n-1, two, one, three);
}

}
public void move(char x,char y){
System.out.println(x+"-->"+y);
}
}

原创粉丝点击