课后习题4.9 Hanoi(汉诺)塔问题。这是一个经典的数学问题:古代有一个梵塔,塔内有3个座A,B,C,开始时A座上有64个盘子,盘子大小不等,大的在下,小的在上(见图4.16)。有一个老和尚想把这64个盘子从A座移到C座,但每次只允许移动一个盘,且在移动过程中3个座上都始终保持大盘在下,小盘在上。在移动过程中可以利用B座,要求编程序打印移出移动的步骤。
#include <iostream>
using namespace std;
int main()
{
void hanoi(int n, char one, char two, char three);
int m;
cout << "input the number of diskes:";
cin >> m;
cout << "The steps of moving " << m << " disks:" << endl;
hanoi(m, 'A', 'B', 'C');
return 0;
}
void hanoi(int n, char one, char two, char three)
//将n个盘从one座借助two座,移到three座
{
void move(char x, char y);
if (n == 1)
move(one, three);
else
{
hanoi(n - 1, one, three, two);
move(one, three);
hanoi(n - 1, two, one, three);
}
}
void move(char x, char y)
{
cout << x << "-->" << y << endl;
}