C++ 實現漢諾塔的實例詳解
更新時間:2017年08月21日 10:10:19 投稿:lqh
這篇文章主要介紹了C++ 實現漢諾塔的實例詳解的相關資料,這里主要說明C++中數據結構的遞歸的應用,需要的朋友可以參考下
C++ 實現漢諾塔的實例詳解
前言:
有A,B,C三塔,N個盤(從小到大編號為1-N)起初都在A塔,現要將N個盤全部移動到C塔(按照河內塔規(guī)則),求最少移動次數以及每次的移動詳細情況。
要求:
需要采用遞歸方法和消除尾遞歸兩種方法編寫。
盤數N由用戶從標準輸入讀入,以一個整數表示,然后請調用兩個方法按照下面例子所述分別在屏幕中輸出結果(正常情況下一個輸入數據會顯示同樣的輸出結果2次)。
實現代碼:
#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ū)交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關文章
C++中聲明類的class與聲明結構體的struct關鍵字詳解
這篇文章主要介紹了C++中聲明類的class與聲明結構體的struct關鍵字,默認情況下結構的所有成員均是公有的,而類的所有成員是私有的,需要的朋友可以參考下2016-01-01