• 汉诺塔递归问提


    一、计思想汉诺塔n个盘子的移动问题,基本就三步:①将n-1个盘子从A移到B。②将第n个盘子从A移到C。③将B上的n-1个盘子从B移到C。

    所以大体上需要两个函数,一个函数用来记录每一步盘子的移动过程,另一个函数用来实现递归操作(递归终止为剩下一个盘子,直接将盘子从A移到C)。

    递归函数是在函数中调用自己,一开始的运算没有完成,却又调用递归函数,一层嵌套一层,直到递归函数的终止,然后在一层一层的输出。

    二、程序流程图

    三、源程序代码

    package hannuota;

    import java.util.Scanner;

    public class hannuota
    {
      public static int quantity=0;//定义移动步数,并赋值为零  
      public static void move(int plate,char a,char b) //盘子每一步的移动位置
      {
        System.out.println("第"+(++quantity)+"次移动:"+"将第"+plate+"个盘子从"+a+"移动到"+b);
        // 将第plate个盘子从a(代号为a,不是A柱)移动到b(同)
      }
      public void process(int n,char a,char b,char c)//移动过程,将n个盘子从a移动到c,b为过渡
      {
        if(n==1) move(1,a,c);//递归终止,n=1,将1盘子从a移到c
        else
        {
        process(n-1,a,c,b);//将n-1个盘子从a移动到b,c为过渡
        move(n,a,c);//将第n个盘子从a移到c
        process(n-1,b,a,c);//将n-1个盘子从b移动到c,a为过渡
        }
      }
      public static void main(String[] args)
      {
        char a='A';
        char b='B';
        char c='C';
        Scanner cin=new Scanner(System.in);
        System.out.print("请输入在A柱子上盘子的个数:");
        int n=cin.nextInt();
        hannuota hannuo=new hannuota();
        hannuo.process(n, a, b, c);
        System.out.println("共移动"+quantity+"次,将所有盘子从A移到C");
        cin.close();
      }
    }

     

    四、结果截图

                                                                        

  • 相关阅读:
    奇虎360安全牛人全球挑战赛无线部…
    Portugal 2 1 minute has Pipansihuan Germany and USA tacit or kick the ball
    求最大公约数和最小公倍数
    JQuery的Ajax跨域请求的解决方式
    从Java到C++——从union到VARIANT与CComVariant的深层剖析
    抽卡概率的測试
    jquery序列化表单以及回调函数的使用
    Notepad++插件安装和使用和打开大文件
    Android开发遇到的问题
    bzoj3068: 小白树
  • 原文地址:https://www.cnblogs.com/cc-9878/p/7657110.html
Copyright © 2020-2023  润新知