汉若塔问题(递归与栈两种方法)

一,递归
目的 将塔x上的n个碟子移到y 借助z
首先将x上的n-1个碟子移到z,然后将最大的移到y
然后把z上的n-1个移到z

void tower(int n, int x, int y, int z) //n个碟子从x→y
{
    //把塔x顶部的n个碟子移到y
    //塔z中转地
    if (n > 0)
    {
        tower(n - 1, x, z, y); //n-1个碟子从x→z
        cout << "Move top disk from tower " << x << " to top of tower " << y << endl;
        tower(n - 1, z, y, x); //n-1个碟子从y→x
    }
}

你可能感兴趣的:(c++)