汉诺塔的问题,为什么能想到用2个递归?内有解法的程序,请指点。
mygis 2001-07-28 03:39:51 汉诺塔问题,就是搬盘子的问题。很多C++的教科书上有它的例子。
我跟踪调试了,知道解法是对的。该解法用了递归,在函数hanoi
中用了2次递归,实在精妙,我就是不太明白为什么他们能想到这样
做,这两步是怎么思考出来的?
下面是汉诺塔问题的源程序。
#include "iostream.h"
void move(char getone,char putone)
{
cout<<getone<<"-->"<<putone<<endl;
}
void hanoi(int n,char one,char two,char three)
{
void move(char getone,char putone);
if(n==1) move(one,three);
else
{
hanoi(n-1,one,three,two);
move(one,three);
hanoi(n-1,two,one,three);
}
}
void main()
{
void hanoi(int n,char one,char two,char three);
int m;
cout<<"Enter the number of disks:";
cin>>m;
cout<<"the steps to moving "<<m<<" disks: "<<endl;
hanoi(m,'A','B','C');
}