热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

java汉诺塔问题_Java如何使用方法来解决汉诺塔问题?

在Java中,如何使用方法来解决汉诺塔的问题?本示例显示了解决汉诺塔问题的方法(3个盘)。packagecom.yiibai;publicclassTo

在Java中,如何使用方法来解决汉诺塔的问题?

本示例显示了解决汉诺塔问题的方法(3个盘)。

package com.yiibai;

public class TowerOfHanoi {

public static void main(String[] args) {

int nDisks = 3;

doTowers(nDisks, 'A', 'B', 'C');

}

public static void doTowers(int topN, char from, char inter, char to) {

if (topN == 1) {

System.out.println("Disk 1 from " + from + " to " + to);

} else {

doTowers(topN - 1, from, to, inter);

System.out.println("Disk " + topN + " from " + from + " to " + to);

doTowers(topN - 1, inter, from, to);

}

}

}

执行上面示例代码,得到以下结果 -

Disk 1 from A to C

Disk 2 from A to B

Disk 1 from C to B

Disk 3 from A to C

Disk 1 from B to A

Disk 2 from B to C

Disk 1 from A to C

示例-2

以下是解决汉诺塔的另一个例子

package com.yiibai;

public class TowerOfHanoi2 {

public static void move(int n, int startPole, int endPole) {

if (n == 0) {

return;

}

int intermediatePole = 6 - startPole - endPole;

move(n - 1, startPole, intermediatePole);

System.out.println("Move " + n + " from " + startPole + " to "

+ endPole);

move(n - 1, intermediatePole, endPole);

}

public static void main(String[] args) {

move(5, 1, 3);

}

}

执行上面示例代码,得到以下结果 -

Move 1 from 1 to 3

Move 2 from 1 to 2

Move 1 from 3 to 2

Move 3 from 1 to 3

Move 1 from 2 to 1

Move 2 from 2 to 3

Move 1 from 1 to 3

Move 4 from 1 to 2

Move 1 from 3 to 2

Move 2 from 3 to 1

Move 1 from 2 to 1

Move 3 from 3 to 2

Move 1 from 1 to 3

Move 2 from 1 to 2

Move 1 from 3 to 2

Move 5 from 1 to 3

Move 1 from 2 to 1

Move 2 from 2 to 3

Move 1 from 1 to 3

Move 3 from 2 to 1

Move 1 from 3 to 2

Move 2 from 3 to 1

Move 1 from 2 to 1

Move 4 from 2 to 3

Move 1 from 1 to 3

Move 2 from 1 to 2

Move 1 from 3 to 2

Move 3 from 1 to 3

Move 1 from 2 to 1

Move 2 from 2 to 3

Move 1 from 1 to 3

¥ 我要打赏

纠错/补充

收藏

加QQ群啦,易百教程官方技术学习群

注意:建议每个人选自己的技术方向加群,同一个QQ最多限加 3 个群。



推荐阅读
author-avatar
笑看人世情9
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有