C++ 實現(xiàn)漢諾塔的實例詳解
C++ 實現(xiàn)漢諾塔的實例詳解
前言:
有A,B,C三塔,N個盤(從小到大編號為1-N)起初都在A塔,現(xiàn)要將N個盤全部移動到C塔(按照河內(nèi)塔規(guī)則),求最少移動次數(shù)以及每次的移動詳細情況。
要求:
需要采用遞歸方法和消除尾遞歸兩種方法編寫。
盤數(shù)N由用戶從標準輸入讀入,以一個整數(shù)表示,然后請調(diào)用兩個方法按照下面例子所述分別在屏幕中輸出結(jié)果(正常情況下一個輸入數(shù)據(jù)會顯示同樣的輸出結(jié)果2次)。
實現(xiàn)代碼:
#include<iostream>
using namespace std;
void move(int count,char start='a',char finish='b',char temp='c')
{
if(count>0)
{
move(count-1,start,temp,finish);
cout<<"Move "<<count<<" from "<<start<<" to "<<finish<<endl;
move(count-1,temp,finish,start);
}
}
void move_without_recursion(int count,char start='a',char finish='b',char temp='c')
{
char swap;
while(count>0)
{
move_without_recursion(count-1,start,temp,finish);
cout<<"Move "<<count<<" from "<<start<<" to "<<finish<<endl;
count--;
swap=start;
start=temp;
temp=swap;
}
}
int main()
{
int count;
cout<<"please enter the number:";
cin>>count;
cout<<"遞歸方法運行過程:"<<endl;
move(count);
cout<<"消除尾遞歸方法運行過程:"<<endl;
move_without_recursion(count);
return 0;
}
如有疑問請留言或者到本站社區(qū)交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關(guān)文章
C++設(shè)計模式之Static Factory模式詳解
這篇文章主要為大家詳細介紹了C++設(shè)計模式之Static Factory模式的相關(guān)資料,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-07-07
一文詳解C++子類函數(shù)為什么不能重載父類函數(shù)
這篇文章主要介紹了一文詳解C++子類函數(shù)為什么不能重載父類函數(shù),文章圍繞主題展開詳細的內(nèi)容戒殺,具有一定的參考價值,需要的朋友可以參考一下2022-09-09
C++中聲明類的class與聲明結(jié)構(gòu)體的struct關(guān)鍵字詳解
這篇文章主要介紹了C++中聲明類的class與聲明結(jié)構(gòu)體的struct關(guān)鍵字,默認情況下結(jié)構(gòu)的所有成員均是公有的,而類的所有成員是私有的,需要的朋友可以參考下2016-01-01

