• 汉诺塔问题(java)


    一、题目描述

            有IIIIII三个底座,底座上面可以放盘子。 初始时, I座上有n个盘子,这些盘子大小各不相同,大盘子在下,小盘子在上,依次排列,如下图1所示。 要求将I座上n个盘子移至III座上,每次只能移动1个,并要求移动过程中保持小盘子在上,大盘子在下,可借座实现移动(不能放在别处或拿在手中)。 编程序输出移动步骤。

     二、解题思路

              这个问题可采用递归思想分析,讲n个盘子由I座移动到III座可以分为三个过程

    1.  将 座上最上面的n-1个盘子移动到 II 座上。
    2.  再将 I 座上最下面一个盘子移至 II 座。
    3.  最后将 II  座上的n-1 个盘子借助 I 座移至 III 座。

            上述过程是把移动n个盘子的问题转化为移动n-1个盘子的问题。 按这种思路, 再将移动n-1个盘子的问题转化为移动n-2个盘子的问题……直至移动1个盘子。

            可以用两个函数来描述上述过程:

            1. 从一个底座上移动n个盘子到另一底座。

            2. 从一个底座上移动 1 个盘子到另一底座。

     三、算法实现

            这里我们柱子的编号用了char, a、b、c 对应 I、II、III  。

    1. package java_code;
    2. public class hanoi {
    3. // 打印移动过程
    4. void Move(char chSour, char chDest){
    5. System.out.println(" Move the top plate of " + chSour + " --> " + chDest);
    6. }
    7. // 递归函数,n为在第I个座上的盘子总数, 后三项为座的名字
    8. void hanoiFun(int n, char I , char II , char III){
    9. if(n==1)
    10. Move(I, III);
    11. else{
    12. // 先将I座上的n-1盘子移动到II座上
    13. hanoiFun(n-1, I, III, II);
    14. // 打印
    15. this.Move(I, III);
    16. // 先将II座上的n-1的盘子移动到III座上,完成
    17. hanoiFun(n-1, II, I, III);
    18. }
    19. }
    20. public static void main(String[] args){
    21. hanoi han = new hanoi();
    22. // 这里我们假设有5个盘子, 三个座分别为a、b、c
    23. han. hanoiFun(5,'a','b','c');
    24. }
    25. }

            终端打印输出的过程:

    1. Move the top plate of a --> c
    2. Move the top plate of a --> b
    3. Move the top plate of c --> b
    4. Move the top plate of a --> c
    5. Move the top plate of b --> a
    6. Move the top plate of b --> c
    7. Move the top plate of a --> c
    8. Move the top plate of a --> b
    9. Move the top plate of c --> b
    10. Move the top plate of c --> a
    11. Move the top plate of b --> a
    12. Move the top plate of c --> b
    13. Move the top plate of c --> a
    14. Move the top plate of b --> a
    15. Move the top plate of b --> c
    16. Move the top plate of a --> c
    17. Move the top plate of a --> b
    18. Move the top plate of c --> b
    19. Move the top plate of a --> c
    20. Move the top plate of b --> a
    21. Move the top plate of b --> c
    22. Move the top plate of a --> c

  • 相关阅读:
    电子战基本概念 (01)
    解决因对EFCore执行SQL方法不熟练而引起的问题
    C# out参数out多个参数
    如何写出高质量的文章:从战略到战术
    跨站脚本攻击(XSS)以及如何防止它?
    Java Double compareTo()方法具有什么功能呢?
    redux-thunk 简单案例,优缺点和思考
    漫谈:编码、哈希、摘要、加密都是什么(别再问“用base64加密行不行”了,会被鄙视)
    打车出行小程序APP定制开发代驾拼车专车
    【VSCode】快捷键+配置代码片段
  • 原文地址:https://blog.csdn.net/ZHY_ERIC/article/details/126378654