解题思路
分析汉诺塔的转移过程,发现汉诺塔问题可以通过分治法分解为许多的小问题,例如A柱上的圆盘个数为n,汉诺塔问题可以分解为:
①:把n-1个A柱子的圆盘通过C柱转移到B柱子上
②:把第n个圆盘从A柱子转移到C柱上
③:把n-2个圆盘从B柱子转移到C柱子上
其中的③,又可以分解为:
①:把n-1个B柱子的圆盘通到A柱子上
②:把第n-1个圆盘由B移到C
③:把n-2个圆盘由A移到C
这样我们递归就明了了。
解题代码
#include<bits/stdc++.h>
using namespace std;
int step=0;
void hannuo(int n,int m,string a,string b,string c ){
//把n个圆盘从a柱通过b柱转移到c柱上
if(n==1){
step++;
if(step==m){
cout<<"#"<<n<<": "<<a<<"->"<<c<<endl;
}
}else{
hannuo(n-1,m,"A","C","B");
step++;
if(step==m){
cout<<"#"<<n<<": "<<a<<"->"<<c<<endl;
//完成一次hannuo()函数之后,依据条件进行输出
}
hannuo(n-1,m,"B","A","C");
}
}
int main(){
int M,N;
cin>>N>>M;
hannuo(N,M,"A","B","C");
cout<<step;
}