高手帮我解释下递归方法的汉诺塔程序的执行顺序?谢谢

来源:百度知道 编辑:UC知道 时间:2024/06/15 11:42:07
void move(char x,char y) //什么时候开始执行这个的?
{
cout<<x<<"-->"<<y<<endl;
}
void hanoi(int n,char a,char b,char c)
{ void move(char x,char y); //x,y指的是什么?
if(n==1)
move (a ,c);
else
{
hanoi(n-1,a,c,b); //这个地方没明白a,b,c的位置不固定呢?
move(a ,c);
hanoi(n-1,b,a,c);//这次有变成b,a,c了
}
}
void main()
{
void hanoi(int n,char a,char b,char c);
int m;
cout<<"please enter the # of rings:";
cin>>m;
cout<<"move"<<m<<" "<<"rings' steps:"<<endl;
hanoi(m,'A','B','C');
}

谢谢。
比如说输入4,请告诉我它的运行流程。

void move(char x,char y) //什么时候开始执行这个的?
{
//move函数定义
//hanoi函数中的move(a ,c); 即是对该函数的调用
cout<<x<<"-->"<<y<<endl;
}
void hanoi(int n,char a,char b,char c)
{
/*
n;需要挪动的环的数目
a;源塔座
b;辅助塔座
c;目标塔座
*/
void move(char x,char y); /*x,y指的是什么? */
//move函数声明
//参数x,y分别表示源塔座,目标塔座
if(n==1) move (a ,c);
else
{ /*轮换辅助塔座*/
hanoi(n-1,a,c,b); //这个地方没明白a,b,c的位置不固定呢?
move(a ,c);
hanoi(n-1,b,a,c);//这次有变成b,a,c了
}
}
void main()
{
void hanoi(int n,char a,char b,char c);
int m;
cout<<"please enter the # of rings:";
cin>>m;
cout<<"move"<<m<<" "<<"rings' steps:"<<endl;
hanoi(m,'A','B','C');
}