遞歸算法三:漢諾塔
問題描述
移動規則:
每次只能移動一個圓盤;
圓盤可以插在A、 B和C中的任何一個塔座上;
任何時刻都不能將一個較大的圓盤壓在較小的圓盤之上。
分析
邊界條件
只有一個圓環時,只需將圓環從第一座塔移到第三座塔
遞歸條件
1、從第一座塔把n-1個圓環移到第二座塔,用第三座塔做輔助
2、從第一座塔把第n個圓環移到第三座塔
3、從第二座塔把n-1個圓環移到第三座塔,用第一座塔做輔助
代碼
簡單漢諾塔遞歸實現
#include<iostream>
using namespace std;
void move(char from, char to){
cout<<"Move"<<from<<"to"<<to<<endl;
}
void hanoi(int n, char first, char second, char third){
if(n==1){
move(first, third);
}else{
hanoi(n-1, first, third, second);
move(first, third);
hanoi(n-1, second, first, third);
}
}
int main(){
int m;
cout<<"the number of diskes:";
cin>>m;
cout<<"move "<<m<<" diskes:\n";
hanoi(m,'A','B','C');
return 0;
}
漢諾塔遞推實現
#include<iostream>
using namespace std;
int main(){
int m;
cin>>m;
long long p = 0;
for(int i=0; i<m; i++){
p=2*p+1;
}
cout<<2*p<<endl;
return 0;
}