递归算法三:汉诺塔 问题描述 移动规则: 每次只能移动一个圆盘; 圆盘能够插在A、 B和C中的任何一个塔座上; 任什么时候刻都不能将一个较大的圆盘压在较小的圆盘之上。ios
分析 边界条件 只有一个圆环时,只需将圆环从第一座塔移到第三座塔 递归条件 一、从第一座塔把n-1个圆环移到第二座塔,用第三座塔作辅助 二、从第一座塔把第n个圆环移到第三座塔 三、从第二座塔把n-1个圆环移到第三座塔,用第一座塔作辅助算法
代码spa
#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; }