C++ 實現(xiàn)漢諾塔的實例詳解
C++ 實現(xiàn)漢諾塔的實例詳解
前言:
有A,B,C三塔,N個盤(從小到大編號為1-N)起初都在A塔,現(xiàn)要將N個盤全部移動到C塔(按照河內(nèi)塔規(guī)則),求最少移動次數(shù)以及每次的移動詳細(xì)情況。
要求:
需要采用遞歸方法和消除尾遞歸兩種方法編寫。
盤數(shù)N由用戶從標(biāo)準(zhǔ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<<"遞歸方法運(yùn)行過程:"<<endl;
move(count);
cout<<"消除尾遞歸方法運(yùn)行過程:"<<endl;
move_without_recursion(count);
return 0;
}
如有疑問請留言或者到本站社區(qū)交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關(guān)文章
c++指針參數(shù)傳遞和引用參數(shù)傳遞的區(qū)別解析
這篇文章主要介紹了c++指針參數(shù)傳遞和引用參數(shù)傳遞的區(qū)別解析,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-07-07

