我需要编写一个递归的河内塔程序,我已经完成了,但是它需要输出由星星代表的圆盘的位置,这就是我遇到的麻烦。每次进行移动时,它都需要输出光盘位置的图片表示。我为 3 张光盘编写了代码,但我需要它更灵活并适用于 3、4 或 5 张光盘。这是我目前拥有的代码。
// This program displays a solution to the Towers of
// Hanoi game.
#include <iostream>
using namespace std;
// Function prototype
void moveDiscs(int, int, int, int, int);
int main()
{
int count = 0;
int NUM_DISCS = 3; // Number of discs to move
const int FROM_PEG = 1; // Initial "from" peg
const int TO_PEG = 3; // Initial "to" peg
const int TEMP_PEG = 2; // Initial "temp" peg
// Play the game.
moveDiscs(NUM_DISCS, FROM_PEG, TO_PEG, TEMP_PEG, count);
cout << "All the pegs are moved!\n";
system("PAUSE");
return 0;
}
//***************************************************
// The moveDiscs function displays a disc move in *
// the Towers of Hanoi game. *
// The parameters are: *
// num: The number of discs to move. *
// fromPeg: The peg to move from. *
// toPeg: The peg to move to. *
// tempPeg: The temporary peg. *
//***************************************************
void moveDiscs(int num, int fromPeg, int toPeg, int tempPeg, int count)
{
if (num > 0)
{
moveDiscs(num - 1, fromPeg, tempPeg, toPeg, count);
cout << "Move a disc from peg " <<fromPeg
<< " to peg " << toPeg <<endl;
count++;
if (fromPeg == 1 && toPeg == 3)
{
if (num == 1)
{
if(count == 3)
cout<<" *"<<endl<< " *"<<endl<< " *"<<endl;
else
cout << "*"<< endl <<"* *"<<endl;
}
else
cout << " *"<<endl <<" * *"<<endl;
}
if (fromPeg==1 && toPeg==2)
cout << "* * *"<<endl;
if (fromPeg ==3 && toPeg==2)
cout << " *"<<endl <<"* *"<<endl;
if (fromPeg==2 && toPeg==1)
cout << "* * *"<<endl;
if (fromPeg==2 && toPeg==3)
cout << " *"<< endl <<"* *"<<endl;
moveDiscs(num - 1, tempPeg, toPeg, fromPeg, count);
}
}