汉诺塔的问题,为什么能想到用2个递归?内有解法的程序,请指点。

mygis mygis 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
汉诺塔问题,就是搬盘子的问题。很多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');
}



...全文
评论 4
收藏 已收藏
分享
返回顶部
mygis
VC/MFC 16,550 成员 421,606 内容