首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

函数递归调用中 汉诺塔 有个地方不明白 求

2012-09-27 
函数递归调用中 汉诺塔有个地方不明白 求高手指点#includestdio.hint main(){void hanoi(int n,char one

函数递归调用中 汉诺塔 有个地方不明白 求高手指点
#include<stdio.h>
int main()
{
void hanoi(int n,char one,char two,int three);
int m;
printf("请输入盘子的数目:");
scanf("%d",&m);
printf("移动 %d 个盘子需要的步骤:\n",m);
hanoi(m,'A','B','C');
  return 0;
}
void hanoi(int n,char one,char two,int three)
{
void move(char x,char y);
if(n==1)
move(one,three);
else
{

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


程序是对的,我不明白的是调用的过程,就是下面的这三句,希望高手指点,谢谢
hanoi(n-1,one,three,two);
move(one,three);
hanoi(n-1,two,one,three);

[解决办法]
要把这个定义看清楚


本想写写,发现百度上写得比我详细多了,你参考一下吧:
先看hanoi(1, one, two, three)的情况。这时直接将one柱上的一个盘子搬到three柱上。注意,这里one柱或three柱到底是A、B还是C并不重要,要记住的是函数第二个参数代表的柱上的一个盘被搬到第四个参数代表的柱上。为方便,将这个动作记为:
one =》three

再看hanoi(2, one, two, three)的情况。考虑到hanoi(1)的情况已经分析过了,可知这时实际上将产生三个动作,分别是:
one =》two
one =》three
two =》three
很显然,这实际上相当于将one柱上的两个盘直接搬到three柱上。

再看hanoi(3, one, two, three)的情况。分析
hanoi(2, one , three, two)
one =》three
hanoi(2, two, one, three)
即:先将one柱上的两个盘搬到two柱上,再将one柱上的一个盘搬到three柱上,最后再将two柱上的两个盘搬到three柱上。这不就等于将one柱上的三个盘直接搬到three柱上吗?

运用归纳法可知,对任意n,
hanoi(n-1, one , three, two)
one =》three
hanoi(n-1, two, one, three)
就是先将one柱上的n-1个盘搬到two柱上,再将one柱上的一个盘搬到three柱上,最后再将two柱上的n-1个盘搬到three柱上。这就是我们所需要的结果!
[解决办法]
如下代码容易理解吧

现在就是转一下脑筋,把这三个函数写成一个函数

C/C++ code
void hanoi1(int n,char here,char there) // 把n盘从here移到there{    printf("move %d from %c to %c\n",n,here,there);}void hanoi2(char here,char temp,char there){    hanoi1(1,here,temp);    hanoi1(2,here,there);    hanoi1(1,temp,there);}void hanoi3(char here,char temp,char there){    hanoi2(here,there,temp);    hanoi1(3,here,there);    hanoi2(temp,here,there);}int main(){    hanoi3('A','B','C'); // 从A柱移到C柱        return 0;} 

热点排行