C++ は「ハノイの塔」コードを再帰的に解決します


リストレコード操作でハノイの塔問題を再帰的に解決する

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

struct Operator
{
    
    
    Operator(int n_, string from_, string to_) : n(n_), origin(from_), destination(to_) {
    
    }
    //第n个
    int n;
    string origin;
    string destination;
};

class HANNUO
{
    
    
public:
    void hannuo(int n, string A, string B, string C);
    void move(int n, string X, string Y);
    list<Operator> caozuo;
};

int main()
{
    
    
    string A{
    
    "A"}, B{
    
    "B"}, C{
    
    "C"};
    HANNUO my_HanNuo;
    int n; // n个盘子
    cin >> n;

    my_HanNuo.hannuo(n, A, B, C);

    cout << endl << "操作次数" << my_HanNuo.caozuo.size() << endl;
    for (auto it = my_HanNuo.caozuo.begin(), it_end = my_HanNuo.caozuo.end(); it != it_end; it++)
    {
    
    
        cout << "第" << it->n << "个\t" << it->origin << "\t" << it->destination << endl;
    }
    return 0;
}

//递归汉诺塔
void HANNUO::hannuo(int n, string A, string B, string C)
{
    
    
    if (n == 1)
    {
    
    
        move(1, A, C);
        return;
    }
    else
    {
    
    
        //递归内容
        hannuo(n - 1, A, C, B);
        //关注的操作,把第n个从A 挪到 C
        move(n, A, C);
        //递归内容
        hannuo(n - 1, B, A, C);
    }
}

void HANNUO::move(int n, string X, string Y)
{
    
    
    caozuo.push_back(Operator(n, X, Y));
    cout << "把第" << n << "个从" << X << "移动到" << Y << endl;
}

おすすめ

転載: blog.csdn.net/qq_41253960/article/details/124330125