| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 503 人关注过本帖
标题:求详细解释汉诺塔c语言递归函数的一段代码是怎么样运行的。谢谢啦
取消只看楼主 加入收藏
咖灬啡
Rank: 1
等 级:新手上路
帖 子:4
专家分:0
注 册:2013-9-15
结帖率:100%
收藏
 问题点数:0 回复次数:0 
求详细解释汉诺塔c语言递归函数的一段代码是怎么样运行的。谢谢啦
用n=3为例吧。。
这个思想我知道。但是用到C语言上就不知道该怎么弄了  很模糊。
想把n個環由1柱移到3柱
就是先把上面n-1個環由1柱移到2柱
然後把底環由1柱移到3柱
再把上面n-1個環由2柱移到3柱.

#include<stdio.h>
#include<stdlib.h>
int main()
{
    int hanoi(int n,char one,char two,char three);
    int m;
    printf("input the number of diskes:");
    scanf("%d",&m);
    printf("The step to moving %d disk:\n",m);
    hanoi(m,'A','B','C');
    system("pause");
    }

int hanoi(int n,char one,char two,char three)
{
    int move(char x,char y);
    if(n==1)
    move(one,three);
    else
    {
        hanoi(n-1,one,three,two);
        move(one,three);
        hanoi(n-1,two,one,three);
        }
    }

int move(char x,char y)
{
    printf("%c-->%c\n",x,y);
    }

其中int hanoi(int n,char one,char two,char three)
{
    int move(char x,char y);
    if(n==1)
    move(one,three);
    else
    {
        hanoi(n-1,one,three,two);
        move(one,three);
        hanoi(n-1,two,one,three);
        }
    }这段看不懂。。运行结果是
input the number of diskes:3
The step to moving 3 disk:
A-->C
A-->B
C-->B
A-->C
B-->A
B-->C
A-->C
请按任意键继续. . .

下面是我觉得应该这样执行的。想着想着就乱了
hanoi(3-1,one,three,two);
{
     int move(char x,char y);
    if(n==1)
    move(one,three);
    else
{

        hanoi(2-1,one,three,two);
        {
            move(one,three);               执行的第一条

        }
        move(one,three);                   执行的第二条  这里我就觉得不对了
        hanoi(2-1,two,one,three);
       {
            move(one,three);              执行的第三条   不知道是move(one,three);   还是move(two,three);              

        }

        }   
}
        
move(one,three);                          执行的第四条
        hanoi(3-1,two,one,three);
{
int move(char x,char y);
    if(n==1)
    move(one,three);
    else
    {
        hanoi(2-1,one,three,two);
        {
        move(one,three);          执行的第五条  不知道是move(one,three); 还是move(one,two);              
        }


        move(one,three);            执行的第六条 不知道是move(one,three); 还是move(one,two);
        hanoi(2-1,two,one,three);
        {
        move(one,three);              执行的第七条 不知道是move(one,three);                还是       move(two,three);     
}

        }
}
这样执行的就是A-->C   A-->C B-->C  B-->C  A-->B A--B   B-->C
搜索更多相关主题的帖子: include system moving number c语言 
2013-09-16 07:42
快速回复:求详细解释汉诺塔c语言递归函数的一段代码是怎么样运行的。谢谢啦
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.016331 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved