汉诺塔的递归与非递归实现

递归版本:

#include <iostream>
#include <time.h>
int count = 0;
using namespace std;
void hanio(int n, char a, char c, char b)
{
    if(n == 1)
    {
        cout<<a<<" -> "<<b<<endl;
        count++;
    }
    else
    {
        hanio(n - 1, a, b, c);
        cout<<a<<" -> "<<b<<endl;
        count++;
        hanio(n - 1, c, a, b);
    }
}

int main()
{
     int n;
    cin>>n;
    clock_t time_start = clock();
    hanio(n, 'a', 'b', 'c');
    clock_t time_end = clock();
    cout<<"The program takes "<<(time_end - time_start)/1.0/1000<<" milliseconds"<<endl;
    return 0;
}

非递归版本:

#include <iostream>
#include <memory.h>
#include <math.h>
#include <time.h>

using namespace std;

int max_k(int i)
{
    if(i==0)
        return 0;
    int k = 0;
    while(i%2==0)
    {
        i/=2;
        k++;
    }
    return k;
}

int main()
{
    int n, k;
    cin>>n;
    clock_t time_start = clock();
    char* a = new char[n];
    memset(a, 'a', n);
    if(n%2==0)
    {
        for(int i=1;i<=pow(2,n)-1;i++)
        {
            k = max_k(i);
            if((k+1)%2)
            {
                char now = a[k];//k+1号盘子现在在哪根柱子上
                char next = (a[k]=='c')?'a':(a[k]+1);//k+1号盘子要移动到哪根柱子上
                cout<<now<<" -> "<<next<<endl;
                a[k] = next;
            }
            else
            {
                char now = a[k];//k+1号盘子现在在哪根柱子上
                char next = (a[k]=='a')?'c':(a[k]-1);//k+1号盘子要移动到哪根柱子上
                cout<<now<<" -> "<<next<<endl;
                a[k] = next;
            }
        }
    }
    else
    {
        for(int i=1;i<=pow(2,n)-1;i++)
        {
            k = max_k(i);
            if((k+1)%2)
            {
                char now = a[k];//k+1号盘子现在在哪根柱子上
                char next = (a[k]=='a')?'c':(a[k]-1);//k+1号盘子要移动到哪根柱子上
                cout<<now<<" -> "<<next<<endl;
                a[k] = next;
            }
            else
            {
                char now = a[k];//k+1号盘子现在在哪根柱子上
                char next = (a[k]=='c')?'a':(a[k]+1);//k+1号盘子要移动到哪根柱子上
                cout<<now<<" -> "<<next<<endl;
                a[k] = next;
            }
        }
    }
    clock_t time_end = clock();
    cout<<"The program takes "<<(time_end - time_start)/1.0/1000<<" seconds"<<endl;
    return 0;
}

最后还输出计算时间,n较小时两者差不多,n大了之后明显非递归更快

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。