我一直试图弄清楚如何用3个参数实现递归函数:Tower(Disk,from,to)。我在google上做了很多研究。所有结果都提出了4个参数递归函数,(disk,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仅用于显示解决方案。
答案 0 :(得分:1)
//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);
}
}
答案 1 :(得分:0)
以下是Algorithm