我一直在尝试找出如何仅使用3个参数来实现递归函数:Tower(Disk,from,to)。我在Google上做了很多研究。所有结果都通过4个参数递归函数(磁盘,a,b,c)得出。任何帮助将不胜感激。
编辑:typedef void (*towersActionFn)(unsigned short fromPost, unsigned short endPost);
void solveTowers(unsigned short nDisks, unsigned short start, unsigned short end, towersActionFn f);
towersActionFn仅用于显示解决方案。
最佳答案
//Pegs are counted 0 to 2
void Tower(int Disk, int Startpeg, int Endpeg)
{
if(Disc <= 0) //Sanity check
return;
if(Disc == 1)
cout << "Move disk from "<<Startpeg<<" to "<<Endpeg<<endl;
else
{
int Other = 3 - Startpeg - Endpeg;
Tower(Disc-1, Startpeg, Other);
Tower(1, Startpeg, Endpeg); //Inline output would do here... Calling for message consistency.
Tower(Disc-1, Other, Endpeg);
}
}
关于c++ - 汉诺塔与C++中的3个参数,塔(磁盘,从,到),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5480753/