zoukankan      html  css  js  c++  java
  • 汉诺塔



    算法:当只有一个盘子的时候,只需要从将A塔上的一个盘子移到C塔上。

                当A塔上有两个盘子是,先将A塔上的1号盘子(编号从上到下)移动到B塔上,再将A塔上的2号盘子移动的C塔上,最后将B塔上的小盘子移动到C塔上。

                当A塔上有3个盘子时,先将A塔上编号1至2的盘子(共2个)移动到B塔上(需借助C塔),然后将A塔上的3号最大的盘子移动到C塔,最后将B塔上的两个盘子借助A塔移动到C塔上。

               当A塔上有n个盘子是,先将A塔上编号1至n-1的盘子(共n-1个)移动到B塔上(借助C塔),然后将A塔上最大的n号盘子移动到C塔上,最后将B塔上的n-1个盘子借助A塔移动到C塔上。

              综上所述,除了只有一个盘子时不需要借助其他塔外,其余情况均一样(只是事件的复杂程度不一样)。

    #include<stdio.h>
    #include<string.h>
    #include<queue>
    #include<stack>
    #include<stdlib.h>
    #include<algorithm>
    #include<iostream>
    using namespace std;
    
    //移动循序遵循从谁到谁借助谁
    //第一个塔为初始塔,中间的塔为借用塔,最后一个塔为目标塔
    int i=1;//记录步数
    void move(int n,char from,char to) //将编号为n的盘子由from移动到to
    {
        printf("第%d步:将%d号盘子%c---->%c
    ",i++,n,from,to);
    }
    void fun(int n,char from,char depend,char to)//将n个盘子由初始塔移动到目标塔(利用借用塔)
    {
        if (n==1)
            move(1,from,to);//只有一个盘子是直接将初塔上的盘子移动到目的地
        else
        {
            fun(n-1,from,to,depend);//先将初始塔的前n-1个盘子借助目的塔移动到借用塔上
            move(n,from,to);              //将剩下的一个盘子移动到目的塔上
            fun(n-1,depend,from,to);//最后将借用塔上的n-1个盘子移动到目的塔上
        }
    }
    int main()
    {
        int n;
        printf("请输入盘子的个数:
    ");
        scanf("%d",&n);
        char x='A',y='B',z='C';
        printf("盘子移动情况如下:
    ");
        fun(n,x,y,z);
        return 0;
    }
    
    

    
  • 相关阅读:
    [LeetCode] Rotate Image
    [LeetCode] Generate Parentheses
    pandas 使用总结
    ConfigParser 读写配置文件
    Cheat Sheet pyspark RDD(PySpark 速查表)
    python随机生成字符
    grep 命令
    hadoop 日常使用记录
    python 2 计算字符串 余弦相似度
    screen命令
  • 原文地址:https://www.cnblogs.com/nyist-xsk/p/7264924.html
Copyright © 2011-2022 走看看