递归解决汉诺塔问题

非常有意思的问题和解法. 递归是真的烧脑啊.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <string>
#include <cstdlib>

using namespace std;

void hanoi(int n, string from,string to,string buffer)
{
if (n == 1)
{
cout << "Move a plate from " + from + " to " + to << endl;
}
else
{
hanoi(n - 1, from, buffer, to);
hanoi(1, from, to, buffer);
hanoi(n - 1, buffer, to, from);
}
}

int main()
{
int n;
cin >> n;
hanoi(n, "A", "C", "B");
system("pause");
return 0;
}