河内的塔有3个参数的C ++,塔(磁盘,从,到)

时间:2011-03-30 01:00:43

标签: c++ recursion

我一直试图弄清楚如何用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仅用于显示解决方案。

2 个答案:

答案 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