求教!汉诺塔问题

桑夏艾 桑夏艾 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
每本C语言书上有一个经典的递归调用,Hanoi,相信大家都知道,研究了很久也没搞清楚hanoi函数是怎么工作的。
源代码:

#include<stdio.h>

void main()
{
void hanoi(int n,char one,char two,char three);/*hanoi原型声明*/

int m;
printf("input the number of disks:");
scanf("%d",&m);
printf("The step to moving %d diskes:\n",m);

hanoi(m,'A','B','C');

}

void hanoi(int n,char one,char two,char three) /*定义hanoi函数*/
{
void move(char x,char y); /*对move函数的声明*/

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

void move(char x,char y)
{
printf("%c-->%c\n",x,y);
}
答案:input the number of diskes:3
The step to moving the 3 diskes:
A-->C
A-->B
C-->B
A-->C
B-->A
B-->C
A-->C
我是这么分析的,main函数中调用hanoi函数,n=3大于1,执行hanoi(n-1),一直执行知道hanoi(1),输出A-->B
然后再执行move(one,three)输出A-->B,在执行hanoi(n-1);
很明显分析有错!请高手指正,给出详细的分析步骤。
...全文

相关推荐

评论 20
收藏 已收藏
分享
返回顶部
桑夏艾
新手乐园 33,315 成员 41,769 内容