现在的位置: 首页 > 综合 > 正文

Hanoi汉罗塔问题

2013年01月04日 ⁄ 综合 ⁄ 共 697字 ⁄ 字号 评论关闭

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);
}
}

抱歉!评论已关闭.