漢諾塔的遞歸與非遞歸實現(xiàn)

遞歸版本:

#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號盤子現(xiàn)在在哪根柱子上
                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號盤子現(xiàn)在在哪根柱子上
                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號盤子現(xiàn)在在哪根柱子上
                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號盤子現(xiàn)在在哪根柱子上
                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大了之后明顯非遞歸更快

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容