java数据结构和算法学习之汉诺塔示例
时间:2021-09-28 14:46:18
package com.tiantian.algorithms;
/**
* _|_1 | |
* __|__2 | |
* ___|___3 | | (1).把A上的4个木块移动到C上。
* ____|____4 | |
* A B C
*
* | | |
* | _|_1 |
* | __|__2 | 要完成(1)的效果,必须要把1、2、3木块移动到B,这样才能把4移动到C
* ____|____4 ___|___3 | 如:代码中的“调用(XX)”
* A B C
*
* | | |
* | _|_1 |
* | __|__2 | 此时,题目就变成了把B上的3个木块移动到C上,回到了题目(1)
* | ___|___3 ____|____4 如:代码中的“调用(YY)”
* A B C
*
* 然后循环这个过程
*
* @author wangjie
* @version 创建时间:2013-3-4 下午4:09:53
*/
public class HanoiTowerTest {
public static void main(String[] args) {
doTowers(4, 'A', 'B', 'C');
}
public static void doTowers(int topN, char from, char inter, char to){
if(topN == 1){
System.out.println("最后把木块1从" + from + "移动到" + to);
}else{
doTowers(topN - 1, from, to, inter); // 调用(XX)
System.out.println("把木块" + topN + "从" + from + "移动到" + to);
doTowers(topN - 1, inter, from ,to); // 调用(YY)
}
}
}
标签:java,数据结构,算法,汉诺塔
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Java 设计模式之责任链模式及异步责任链详解
2021-08-08 19:14:23
![](https://img.aspxhome.com/file/2023/9/72639_0s.png)
使用Android studio创建的AIDL编译时找不到自定义类的解决办法
2023-06-23 10:59:41
SpringMvc+Mybatis+Pagehelper分页详解
2021-08-13 14:15:11
SpringCloud 搭建企业级开发框架之实现多租户多平台短信通知服务(微服务实战)
2022-12-04 13:22:53
JPA中EntityListeners注解的使用详解
2023-08-04 21:39:18
java基础(System.err和System.out)详解
2022-10-23 23:27:37
详解java设计模式中的门面模式
2021-08-17 18:16:25
基于spring-boot和docker-java实现对docker容器的动态管理和监控功能[附完整源码下载]
2022-02-04 00:41:18
![](https://img.aspxhome.com/file/2023/6/82446_0s.png)
一篇文章教你如何用多种迭代写法实现二叉树遍历
2023-12-23 04:03:29
Javacsv实现Java读写csv文件
2022-02-16 01:10:15
44条Java代码优化建议
2023-12-22 06:03:49
![](https://img.aspxhome.com/file/2023/6/62776_0s.png)
springboot2.0整合dubbo的示例代码
2021-11-30 06:07:11
![](https://img.aspxhome.com/file/2023/5/78045_0s.png)
JAVA 枚举单例模式及源码分析的实例详解
2022-04-30 23:57:44
C++程序中启动线程的方法
2023-06-28 03:35:02
SpringBoot Mybatis Plus公共字段自动填充功能
2022-09-01 12:22:33
Collections.shuffle()方法实例解析
2021-09-17 18:51:38
解决response.setHeader设置下载文件名无效的问题
2021-08-15 20:43:54
java多线程实现下载图片并压缩
2023-01-17 22:28:34
springboot使用之多个filter的执行顺序以及配置方式
2023-11-09 09:30:59
![](https://img.aspxhome.com/file/2023/5/59045_0s.jpg)
mvc开启gzip压缩示例分享
2022-05-03 08:34:29