眼底充血是什么原因:c程序~递归问题

来源:百度文库 编辑:高考问答 时间:2024/04/29 19:09:19
#include"stdio.h"
void move(char x,char y)
{
printf("%c-->%c\n",x,y);
}
void hanoi(int n,char one,char two,char three)
{
if(n==1)move(one,three);
else{
hanoi(n-1,one,three,two);
move(one,three);
hanoi(n-1,two,one,three);
}
}
void main()
{int m;
printf("input the number of diskes:");
scanf("%d",&m);
printf("the step to moving %3d diskes:\n",m);
hanoi(m,'A','B','C');
}
谁能解释一下中间的递归过程
比如n=2;
hanoi(n-1,one,three,two);
move(one,three);
hanoi(n-1,two,one,three);
这部分怎么进行能不能具体点
一部部运行能不能写出来啊~

汉诺塔问题是经典的递归问题:
#include"stdio.h"
void move(char x,char y)
{
printf("%c-->%c\n",x,y);
}
★void hanoi(int n,char one,char two,char three)
{
if(n==1)move(one,three);
//只有一个盘子的话很简单,直接one->three
//若有2个以上的盘子,则执行以下代码。
else{
hanoi(n-1,one,three,two); //到★处执行,直到n=1
move(one,three);
hanoi(n-1,two,one,three); //到★处执行,直到n=1
}
}
void main()
{int m;
printf("input the number of diskes:");
scanf("%d",&m);
printf("the step to moving %3d diskes:\n",m);
hanoi(m,'A','B','C');
}
类似的问题还有八皇后问题等。
QQ;547758555
E-Mail:jiaqi369@gmail.com

很多C语言的书籍上都有讲

这道程序是汉诺塔问题:

目的:把n个东西从A处移动到C处。

分析:
如果只有一个:直接搬过去即可: if(n==1) printf("%c---%c\n",a,c);
否则,把除最下面的那个以外的先放到b处: hanoi(n-1,a,c,b );
再把最下面的那个搬到c处;
于是问题就变成了:把n-1个东西从b处移动到c处: hanoi(n-1,b,a,c);
递归就开始了……
n-1,n-2,……,2,1 结束

过程大致就是这样。