To move n disks from peg 1 to peg 3, using peg 2 as a temporary peg:
If n > 0 Then
Move n-1 disks from peg 1 to peg 2, using peg 3 as a temporary peg.
Move a disk from peg 1 to peg 3.
Move n-1 disks from peg 2 to peg 3, using peg 1 as a temporary peg.
End If
现在来编写一个实现这个解决方案的函数,打印解决游戏的一系列动作。以下代码将使用名称而不是数字来描述柱子。该函数的目标是使用临时柱子(peg3)将一叠圆盘从源柱子(peg1)移动到目标柱子(peg2)。以下是函数的代码:
void moveDisks(int n, string source, string dest, string temp)
{
if (n > 0)
{
//将n-1圆盘从源柱子移动到临时柱子
//使用目标柱子作为临时柱子
moveDisks(n - 1, source, temp, dest);
//将圆盘从源柱子移动到目标柱子
cout << "Move a disk from " << source << " to " << dest << endl;
//将n-1圆盘从临时柱子移动到目标柱子
//使用源柱子作为临时柱子
moveDisks(n - 1, temp, dest, source);
}
}
基本情况在 n = 0 时发生,并且没有要移动的圆盘。在这种情况下,函数调用将不做任何事情返回。下面的程序演示了该函数。
// This program displays a solution to the towers of Hanoi game.
#include <iostream>
#include <string>
using namespace std;
// Function prototype
void moveDisks(int, string, string, string);
int main()
{
// Play the game with 3 disks
moveDisks (3, "peg 1", "peg 3", "peg 2");
cout << "All the disks have been moved!";
return 0;
}
void
moveDisks(int n, string source, string dest, string temp)
{
if (n > 0)
{
// Move n-1 disks from source to temp
// using dest as the temporary peg
moveDisks(n-1, source, temp, dest);
// Move a disk from source to dest
cout << "Move a disk from " << source << " to " << dest << endl;
// Move n-1 disks from temp to dest
// using.source as the temporary peg
moveDisks(n-1, temp, dest, source);
}
}
程序输出结果:
Move a disk from peg 1 to peg 3
Move a disk from peg 1 to peg 2
Move a disk from peg 3 to peg 2
Move a disk from peg 1 to peg 3
Move a disk from peg 2 to peg 1
Move a disk from peg 2 to peg 3
Move a disk from peg 1 to peg 3
版权说明:Copyright © 广州松河信息科技有限公司 2005-2025 版权所有 粤ICP备16019765号
广州松河信息科技有限公司 版权所有