注册 登录
编程论坛 C++教室

汉诺塔问题的移动方法唯一吗?

零下八度 发布于 2010-09-16 20:31, 1032 次点击
使用函数递归实现
6 回复
#2
x_wangyue2010-09-17 00:21
你说的是使用函数递归调用做吗?
使用函数递归倒是会做,其余倒是没掌握!
这是我原来做题时弄的,不知道对不对你胃口:
include <iostream>

using namespace std;

int main()
{
    void hannuota(int,char,char,char);
    int n;
    cout<<"input the numbers of disks:"<<endl;
    cin>>n;
    hannuota(n,'A','B','C');
    return 0;
}

void hannuota(int n,char x,char y,char z)
{
    void move(char,int,char);
    if(n==1)
        move(x,1,z);

    else
    {
        hannuota(n-1,x,z,y);
        move(x,n,z);
        hannuota(n-1,y,x,z);
    }
}

void move(char getone,int n,char putone)
{
    static k=1;
    cout<<k<<n<<getone<<putone<<endl;
    if(k++%3==0)
        cout<<endl;
}
#3
零下八度2010-09-17 12:47
你的语句我看过了。。。我有两个问题,

第一在主函数里调用hannuota(n,'A','B','C');这个为什么A B C还要加引号。。。

第二 在定义hannuota这个函数的时候可以改成这样不。。


void hannuota(int n,char x,char y,char z)
{
    void move(char,int,char);
    if(n==1)
        move(x,1,z);

    else
    {
        hannuota(n-1,x,z,y);
        move(x,n,z);
        hannuota(n-1,y,z,x);
        hannuota(n-1,x,y,z);   //用这两句话替代你的那一句。。。
    }
}
#4
南国利剑2010-09-17 15:25
加单引号是因为ABC是char类型的、
#5
南国利剑2010-09-17 15:28
汉诺伊塔问题是典型的递归问题。
移动的规则是固定的。但是,是否有其他方法,你可以百度一下。
#6
x_wangyue2010-09-18 19:36
回复 3楼 零下八度
只要逻辑是对的当然可以啦
#7
weble2010-09-19 23:14
怎么证明方法是唯一的?
1