汉诺塔算法

本文详细介绍了使用递归算法和栈实现汉诺塔问题的解决方案。通过递归方法清晰地展示了如何将不同数量的盘子从一个柱子移动到另一个柱子,并提供了完整的C++代码实现。此外,还探讨了利用栈来模拟递归过程的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*
*               Hanoi思路:用递归//栈
*假设开始柱子:A,中间柱子:B,目标柱子:C
*第一步:将n-1个盘子从A借助C移到B
*第二步:将第n个盘子从A到C
*第三步:将n-1个盘子从B借助A移到C
*
*/




//递归算法:

#include <iostream>
#include<stdio.h>
using namespace std;

void Hanoi(int plate, char A,char B,char C);

static int count;//计算移动的总次数

int main()
{
    int plate;
    while(cin>>plate)
    {
        getchar();
        char start;
        char depend;
        char destination;
        scanf("%c%*c%c%*c%c%*c",&start,&depend,&destination);//输入起始柱,中间柱和目标柱
        count=0;
        Hanoi(plate,start,depend,destination);
        cout<<endl;
    }
    return 0;
}

void Hanoi(int plate, char A,char B,char C)
{
    if(plate==1)
       {
        cout<<"第"<<++count<<"次:";
        cout<<"第"<<plate<<"个盘子从"<<A<<"移到"<<C<<endl;
       }
    else
    {
        Hanoi(plate-1,A,C,B);//将n-1个从 A借助 C 移到 B
        cout<<"第"<<++count<<"次:";
        cout<<"第"<<plate<<"个盘子从"<<A<<"移到"<<C<<endl;//将最底下的最大盘子从A移到C
        Hanoi(plate-1,B,A,C);//将B上的n-1个盘子由B借助A移到C
    }
}

//栈

#include<iostream>
#include<stack>
#include<stdio.h>
using namespace std;

struct EveryTime//每次移动
{
    int CurPlateNum;
    char start;
    char dependent;
    char destination;
    EveryTime(){}
    EveryTime(int n, char A, char B, char C):CurPlateNum(n),start(A),dependent(B),destination(C){}
};

int main()
{
    stack<EveryTime> stk;
    EveryTime cur;
    int n;
    int count;//统计需要移动的次数

    while(cin>>n)
    {
        getchar();
        char start;
        char depend;
        char destination;
        scanf("%c%*c%c%*c%c%*c",&start,&depend,&destination);//输入起始柱,中间柱和目标柱

        count=0;
        stk.push(EveryTime(n,start,depend,destination));
        while(!stk.empty())
        {
            cur=stk.top();//用cur保存栈顶,下面用cur进行讨论
            stk.pop();//弹出栈顶

            if(cur.CurPlateNum==1)
            {
                cout<<"第"<<++count<<"次:";
                cout<<"第"<<cur.CurPlateNum<<"个盘子从"<<cur.start<<"移到"<<cur.destination<<endl;
            }

            else//根据栈先进后出特点应该将顺序倒过来.因为递归可以独立进行,而栈先进去的元素等会晚执行
            {
                stk.push(EveryTime(cur.CurPlateNum-1,cur.dependent,cur.start,cur.destination));//将n-1个从B(dependent)借助A(start)移到C(destination)
                stk.push(EveryTime(1,cur.start,cur.dependent,cur.destination));//将第n个由A(start)移到C(destination)
               stk.push(EveryTime(cur.CurPlateNum-1,cur.start,cur.destination,cur.dependent));//将n-1个从A(start)借助C(destination)移到B(depenent)
            }

        }

    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

haibianyoushark

如有所帮助,请留下碎银,多谢!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值