诛仙三青云挂无双:VC++中河内塔问题谁能解释一下

来源:百度文库 编辑:高考问答 时间:2024/04/28 21:29:58
就是VC++中<函数的递归调用>中出现的一个例题.谁能详细的说一下具体的解题思路和过程

是汉罗塔吧?
递归:一种调用自身的循环,这种循环的操作具有一定的相似性.如:n!;
int f(int n)
{
if(n<0)retrun 0;
if(!n)return 1;
else return n*f(n-1);
}
说简单点就是:在函数中调用自身!

汉罗塔的思路大概如下:
把n个盘子从a移到c,有以下步骤
1.把n-1个盘子从a移到b
2.把第n个盘子从a移到c
3.把n-1个盘子从b移到c

给个代码吧:
编译通过, 设三根柱子为A,B,C 盘子从下至上依次为1,2,3。。。n-1,n

#include <iostream.h>
#include <conio.h>
class hanoi
{
int a[10];
int N;
public:
void init(int n);
void fn(int m);
};
void hanoi::init(int n)
{
N=n;
for (int i=1; i<=N; i++)
{
if (i%2==1)
a[i]=2;
else
a[i]=1;
}
}
void hanoi::fn(int m)
{
if (m<N)
fn(m+1);
cout<<m<<"->"<<(char)('A'+a[m])<<endl;
if (m%2==1)
a[m]=(a[m]+2)%3;
else
a[m]=(a[m]+1)%3;
if (m<N)
fn(m+1);
}
void main()
{
hanoi h;
int n;
for (; ;)
{
clrscr();
cout<<"Input the number of dish (<10, input 0 to quit):";
cin>>n;
if (n<0 || n>10)
continue;
else if (n==0)
break;
else
{
h.init(n);
h.fn(1);
}
cout<<"press any key to continue";
getch();
}
}
建议你单步dubeg,有助于你的理解!
希望对你有帮助!