汉诺塔问题 来个好心人吧!!!

来源:百度知道 编辑:UC知道 时间:2024/07/03 03:48:37
#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(2-1,one,three,two),one,three,two 里放的是 A C B吗?
给做个详细解答 谢谢大家 小弟初学 态度不错脑子不好
h(3-1,one,three,two),one,three,two 里放的是 ‘A ’ ‘C’ ‘ B’吗?

//你可以把函数写成void h(int, char, char, char)
//调用时候把参数一个个按顺序给参数列表中的参数,和函数中的参数名字无关

//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,d