Java递归来实现汉诺塔游戏,注释详细
作者:钢铁的面条 时间:2023-07-05 10:33:52
我们很容易能想到,可以用递归来实现汉诺塔游戏。因为要将n(n>1)个盘子从“源”柱子移到“目标”柱子,我们要先把n-1个盘子从“源”柱子移到“辅助”柱子上,然后把最底下那一个盘子移到目标柱子上,最后把“辅助柱”上的n-1个盘子移动到目标柱子上。n==1时直接移到目标柱上,也是递归的出口。
有了以上思路的铺垫,就可以开始实现代码了。
public class HanoiDemo {
public static int hanoiCalledCount = 0;//成员变量记录操作次数
//汉诺塔游戏是一种二路递归
public static void main(String[] args) {
hanoi(3,"A","B","C");
System.out.println("执行"+hanoiCalledCount+"步");
}
public static void hanoi(int n,String source,String target,String assist){
if(n<=0){
System.out.println("n要大于零");
}
if(n==1){//递归的出口,n==1时直接移到目标柱上
System.out.printf("把一个盘子从%s柱子上移动到%s柱子上\n",source,target);
hanoiCalledCount++;//计数器加一
}else{
//先把n-1个盘子从“源”柱子移到“辅助”柱子上
hanoi(n-1,source,assist,target);
//把最底下那一个盘子移到目标柱子上
System.out.printf("把一个盘子从%s柱子上移动到%s柱子上\n",source,target);
hanoiCalledCount++;//计数器加一
//把“辅助柱”上的n-1个盘子移动到目标柱子上
hanoi(n-1,assist,target,source);
}
}
}
运行结果如下,大家可以尝试验证一下是否正确。
当n==2时,要操作3次
当n==3时,要操作7次
当n==4时,要操作15次
相信大家已经猜出规律了,操作次数==n^2-1
可见,随着盘子个数n的增加,操作次数以n^2增加,所以,自己玩汉诺塔游戏的是时候建议数字不要超过20。
来源:https://blog.csdn.net/m0_53653818/article/details/121524416
标签:Java,汉诺塔游戏,汉诺塔算法
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
C#编程调用Cards.dll实现图形化发牌功能示例
2022-10-24 12:02:54
![](https://img.aspxhome.com/file/2023/8/98268_0s.jpg)
Java swing实现支持录音等功能的钢琴程序
2022-08-21 12:30:16
![](https://img.aspxhome.com/file/2023/1/80951_0s.jpg)
详解Java中的println输入和toString方法的重写问题
2022-12-24 05:26:33
![](https://img.aspxhome.com/file/2023/8/89568_0s.jpg)
详解使用Spring Boot开发Restful程序
2023-01-24 09:20:09
![](https://img.aspxhome.com/file/2023/3/128863_0s.png)
java多线程-读写锁原理
2021-07-20 17:28:52
Spring容器的创建过程之如何注册BeanPostProcessor详解
2022-02-17 08:39:09
![](https://img.aspxhome.com/file/2023/2/65172_0s.png)
Spring中的注解@Autowired实现过程全解(@Autowired 背后的故事)
2023-01-01 06:02:53
C#访问SqlServer设置链接超时的方法
2022-11-19 17:43:21
Java中关于字符串的编码方式
2023-01-30 04:59:45
![](https://img.aspxhome.com/file/2023/3/110823_0s.png)
java实现上传文件类型检测过程解析
2023-11-09 12:04:21
Android基础之隐藏标题栏/设置为全屏/横竖屏切换
2022-06-22 14:29:35
![](https://img.aspxhome.com/file/2023/8/137468_0s.jpg)
Springboot整合微信支付(订单过期取消及商户主动查单)
2023-05-15 23:40:50
![](https://img.aspxhome.com/file/2023/1/62511_0s.png)
C# 两种方式反编译修改源码(dnspy,ildasm & ilasm)
2022-04-29 18:48:56
![](https://img.aspxhome.com/file/2023/2/104312_0s.png)
配置Android SDK
2023-12-05 09:57:29
![](https://img.aspxhome.com/file/2023/4/102614_0s.png)
Android系统音量条实例代码
2022-05-26 15:20:48
![](https://img.aspxhome.com/file/2023/2/118982_0s.png)
Java生产1-100的随机数简单实例(分享)
2021-08-15 02:52:28
C#自定义画刷原理解析
2021-06-19 19:17:32
![](https://img.aspxhome.com/file/2023/0/98260_0s.jpg)
C#操作EXCEL DataTable转换的实例代码
2022-05-18 04:25:15
Springboot actuator生产就绪功能实现解析
2021-07-23 12:57:06
Java Map接口概述和常用方法详解
2022-07-29 14:19:06
![](https://img.aspxhome.com/file/2023/8/103998_0s.png)