递归解决汉诺塔问题
用一个list记录 *** 作
#include
#include
#include
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;
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)