[Reserved] Tower of Hanoi recursive and non-recursive algorithm

Source: https://blog.csdn.net/computerme/article/details/18080511

Recursive algorithm:

/*汉诺塔递归算法*/
#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;
}
/ * Tower of Hanoi non-recursive algorithm * / 
#include <the iostream>
 the using  namespace STD;
 const  int NMAX is = 64 ;
 struct Pillar {
     int Store [NMAX is];
     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;
}

 

Guess you like

Origin www.cnblogs.com/jiading/p/11456451.html