[转载]汉诺塔递归与非递归算法


来源: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;
}

优质内容筛选与推荐>>
1、linux光盘、U盘的挂载与卸载
2、Mac 端口转发
3、perl链接oracle
4、在Release模式下的调试
5、用HttpClient抓取人人网高校数据库(省,高校,院系三级级联)


长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号





    联系我们

    欢迎来到TinyMind。

    关于TinyMind的内容或商务合作、网站建议,举报不良信息等均可联系我们。

    TinyMind客服邮箱:support@tinymind.net.cn