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);
}
}
/*
* 汉罗塔问题
*/
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);
}
}
- Hanoi汉罗塔问题
- 汉罗塔hanoi问题之递归
- Hanoi 问题
- hanoi问题
- Hanoi问题
- Hanoi问题
- hanoi问题
- hanoi问题
- Hanoi问题
- Hanoi问题
- hanoi问题
- Hanoi问题
- Hanoi 问题
- hanoi问题
- hanoi问题
- Hanoi双塔问题(hanoi)
- 递归法求解汉罗塔hanoi问题
- Hanoi塔问题
- sql中的reverse功能
- (dijkstra) MPI Maelstrom (P1502)
- android中避免大图片解析导致内存溢出 OutOfMemoryError的优化方法
- 将日志信息(系统性能参数)记录到MongoDB --- 1:准备工作
- Apache Commons fileUpload实现文件上传
- Hanoi汉罗塔问题
- [计算机基础]Mod Function and Negative Numbers
- VC下代替system函数的API
- 指针练习三
- Service学习(二)之bindService 的实现
- python操作mysql
- python学习笔记之python中处理中文
- 网络-REST与SOAP之对比
- 第一个Android应用程序