前言
参考文献:数据结构 【严蔚敏】
这个小游戏,以前玩过,当时玩的很吃力。对着书,然后实现出来的,感觉还挺有意思
代码
#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