算法 汉诺塔问题

做一个豁达而努力的自己。

汉诺塔问题是一个典型的递归问题,其实也就是按照自己思路写出来就行了,,,

有3柱塔A,B,C,A为初始塔,B为借助塔,C为目标塔,,,

目标是要将A上的圆盘借助B运到C,

规则:1.每次只能移动一个圆盘,

          2.圆盘可以放到A,B,C中任意一个塔上,

          3.任意时刻不可以将较大圆盘放在较小圆盘上面,

分析(借助代码):

    当A上只有1个圆盘时,直接可以将圆盘运到C,

    当A上有2个圆盘时,先将1号(最上面的小的)圆盘运到B上,再将2号圆盘运到C上,再将1号圆盘从B运到C上,

    当A上有3个圆盘时,先将1,2号圆盘运到B上,再将3号圆盘运到C上,再将1,2号圆盘从B运到C上,

    当A上有n个圆盘时,先将n-1个圆盘运到B上,再将n号圆盘运到C上,再将n-1个圆盘从B运到C上,

其实也就是按着这个思想,写函数就可以了,,,

代码:

#include <iostream>
using namespace std;

void move(int n, char a, char c)
{
    cout << n << " " << a << " -> " << c << endl;;
}
void Hannuota(int n, char a, char b, char c)
{
    if(n == 1)  //当A中只有一个圆盘时,将1号盘从A移动到C上
        move(1, a, c);
    else
    {
        Hannuota(n - 1, a, c, b);   //将n-1个圆盘从A借助C移动到B上
        move(n, a, c);  //将最后的n号盘从A移动到C上
        Hannuota(n - 1, b, a, c);   //再将n-1个盘从B借助A移动到C上
    }
}
int main()
{
    char a = 'A', b = 'B', c = 'C';
    int n;
    cout << "输入A塔上圆盘的个数:";
    cin >> n;
    Hannuota(n, a, b, c);
    return 0;
}

运行结果:


猜你喜欢

转载自blog.csdn.net/qq_37043100/article/details/79711372