递归 汉诺塔 问题 快点来个人吧 急死了 出事了

来源:百度知道 编辑:UC知道 时间:2024/06/08 12:39:59
#include<stdio.h>
void main()
{
void h(int n,char one,char two,char three);
h(3,'A','B','C');
}
h(int n,char one,char two,char three)
{
if(n==1)
printf("%c---->%c\n",one,three);
else
h(n-1,one,three,two)
printf("%c-->%c\n",one,three);
h(n-1,two,one,three)
}
那个好心人来给我讲讲吧 函数调用时值是如何传递的;
比如说 h(3,'A','B','C');调用h函数时到这h(n-1,one,three,two),
h(3-1,one,three,two),one,three,two 里放的是 A C B吗?
给做个详细解答 谢谢大家 小弟初学 态度不错脑子不好

呵呵,这样不好理解的话,我们把变量换个名称吧。

void solve(int disks,int source,int temp,int destination)
{
if(disks==1)
printf("%d---->%d\n",source,destination);
else
solve(disks-1,source,destination,temp)
printf("%d-->%d\n",source,destination);
solve(disks-1,temp,source,destination)
}

disks表示圆盘的个数,source表示所有盘子原来在的那根柱子(第一根), 而destination表示要移动到目标的那根柱子(第三根),temp则表示第二根柱子,是用来临时存放圆盘的.

递归的过程不是分为三个小过程么?

1.从1号柱子source移动n-1个圆盘到2号柱子temp,用3号柱子做临时存放。

根据这句话的理解,可以写成这样
solve(disks-1,source,destination,temp)
为什么呢?
看函数声明吧~
void solve(int disks,int source,int temp,int destination)
前面说了,source表示原来盘子在的位置,temp表示临时存放盘子的位置,destination表示最终要移动到的位置。
那么对第一句话的意思,就可以写出:
solve(disks-1,source,destination,temp); //(*)
把disks-1个圆盘从原来的柱子1号位置,要先移动到2号柱子的位置上,所以2号柱子此时是做为最终要移动到的位置,而3号柱子是暂时存放的。所以这时候的(*)号语句中的temp是最终要移动到的位置。而destination作为临时存放的柱子.

2 从1号柱子移动最后一个圆盘到3号柱子上