c++使用递归实现汉诺塔

前言

参考文献:数据结构 【严蔚敏】
这个小游戏,以前玩过,当时玩的很吃力。对着书,然后实现出来的,感觉还挺有意思

代码

#include<iostream>
#include<string>
using namespace std;

void move(const std::string& src, const int number, const std::string& dst, int& cnt)
{
    std::cout <<cnt<< ": move "<<number <<" from "<< src <<" to "<< dst <<std::endl;
    cnt +=1;
}

void Hanoi(int n, std::string& x, std::string& y, std::string& z, int& cnt)
{    

    if(n==1)
    {
        move(x,1,z, cnt);
    }
    else
    {
        Hanoi(n-1, x, z, y, cnt);
        move(x, n, z, cnt);
        Hanoi(n-1, y, x, z, cnt);
    }
    
}

int main()
{
    std::string X("X");
    std::string Y("Y");
    std::string Z("Z");

    int cnt = 0;

    Hanoi(4,X,Y,Z,cnt);


    return 0;
}

结果

0: move 1 from X to Y
1: move 2 from X to Z
2: move 1 from Y to Z
3: move 3 from X to Y
4: move 1 from Z to X
5: move 2 from Z to Y
6: move 1 from X to Y
7: move 4 from X to Z
8: move 1 from Y to Z
9: move 2 from Y to X
10: move 1 from Z to X
11: move 3 from Y to Z
12: move 1 from X to Y
13: move 2 from X to Z
14: move 1 from Y to Z
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值