C++ 實(shí)現(xiàn)漢諾塔的實(shí)例詳解
前言:
有A,B,C三塔,N個(gè)盤(從小到大編號(hào)為1-N)起初都在A塔,現(xiàn)要將N個(gè)盤全部移動(dòng)到C塔(按照河內(nèi)塔規(guī)則),求最少移動(dòng)次數(shù)以及每次的移動(dòng)詳細(xì)情況。
要求:
需要采用遞歸方法和消除尾遞歸兩種方法編寫。
盤數(shù)N由用戶從標(biāo)準(zhǔn)輸入讀入,以一個(gè)整數(shù)表示,然后請調(diào)用兩個(gè)方法按照下面例子所述分別在屏幕中輸出結(jié)果(正常情況下一個(gè)輸入數(shù)據(jù)會(huì)顯示同樣的輸出結(jié)果2次)。
實(shí)現(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<<"遞歸方法運(yùn)行過程:"<<endl; move(count); cout<<"消除尾遞歸方法運(yùn)行過程:"<<endl; move_without_recursion(count);return 0;}如有疑問請留言或者到本站社區(qū)交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
新聞熱點(diǎn)
疑難解答