如何使用递归而不是打印来返回河内塔的步骤

问题描述

我需要有关返回河内塔楼台阶的帮助。下面是我的代码和输出。

这是我的头文件

#ifndef Hanoi_h
#define Hanoi_h
#include <vector>
#include <string>
#pragma once

using namespace std;

class Hanoi {
private:
    int _num_poles;
    int _num_discs;
    std::vector<vector<vector<string>>> _cache;

    std::string lookup_moves(int num_discs,int src,int dst);
    std::string get_moves(int num_discs,int dst,int tmp);
public:
// Use freebie default constructor
    std::string solve(int num_discs,int tmp);
    friend class Tests; // Don't remove this line
};

    #include <iostream>
#include <vector>
#include "Hanoi.h"
#include <string>
#include <algorithm>

这是我的.cpp文件

using namespace std;

string Hanoi::get_moves(int num_discs,int tmp){
    if(num_discs == 0){
        return "";
    }
    get_moves(num_discs-1,src,tmp,dst);
    // the print statement
    string step = to_string(src) + "->" + to_string(dst) + "\n";
    get_moves(num_discs-1,dst,src);

return step;
};

这是我尝试运行时的错误输出。如您所见,当我尝试放置get_moves(2,2,3,1)时,它仅返回一步:

2->3

program ended with exit code: 0

因此,基本上get_moves方法必须返回发生的所有步骤。但不打印它,只需返回步骤,因为代码将由代码检查器检查。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)