来源:https://blog.csdn.net/computerme/article/details/18080511
递归算法:
/*汉诺塔递归算法*/ #include<iostream> using namespace std; //use a number of 1,2 and 3 to stand for the three pillars void hanio(int n,int from,int to,int by){ if(n!=1){ hanio(n-1,from,by,to); hanio(1,from,to,0); hanio(n-1,by,to,from); } else{ cout<<"从"<<from<<"放到"<<to<<endl; } } int main(){ int n; cin>>n; hanio(n,1,3,2); cout<<'!'<<endl; }
/*汉诺塔非递归算法*/ #include<iostream> using namespace std; const int NMAX=64; struct pillar{ int store[NMAX]; int Top; char label; int top(){ return store[Top-1]; } int pop(){ Top--; return store[Top]; } void push(int x){ store[Top]=x; Top++; } }; void hanio(pillar ss[],long n){ int k=0; int i=0; while(k<n){ int temp=ss[i%3].pop(); ss[(i+1)%3].push(temp); cout<<temp<<"号从"<<ss[i%3].label<<"移动到"<<ss[(i+1)%3].label<<endl; k++; if(k<n){ if(ss[(i+2)%3].top()==0|| ss[(i+2)%3].top()>ss[(i)%3].top()){ int temp=ss[(i)%3].pop(); ss[(i+2)%3].push(temp); cout<<temp<<"号从"<<ss[(i)%3].label<<"移动到"<<ss[(i+2)%3].label<<endl; } else{ int temp=ss[(i+2)%3].pop(); ss[(i)%3].push(temp); cout<<temp<<"号从"<<ss[(i+2)%3].label<<"移动到"<<ss[(i)%3].label<<endl; } k++; } i++; } } long Pow(int a,int b){ long ans=a; for(int i=0;i<b-1;i++){ ans*=a; } return ans; } void initialize(pillar test[],int n){ test[0].label='A'; test[0].Top=n; test[1].Top=test[2].Top=0; for(int i=0;i<n;i++){ test[0].store[i]=n-i; test[1].store[i]=test[2].store[i]=0; } if(n%2==0){ test[1].label='B'; test[2].label='C'; } else{ test[1].label='C'; test[2].label='B'; } } int main(){ int n; cin>>n; pillar use[3]; initialize(use,n); long powAns=Pow(2,n)-1; hanio(use,powAns); cout<<"hi"<<endl; }