欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C++ 實(shí)現(xiàn)漢諾塔的實(shí)例詳解

 更新時(shí)間:2017年08月21日 10:10:19   投稿:lqh  
這篇文章主要介紹了C++ 實(shí)現(xiàn)漢諾塔的實(shí)例詳解的相關(guān)資料,這里主要說(shuō)明C++中數(shù)據(jù)結(jié)構(gòu)的遞歸的應(yīng)用,需要的朋友可以參考下

C++ 實(shí)現(xiàn)漢諾塔的實(shí)例詳解

前言:

有A,B,C三塔,N個(gè)盤(pán)(從小到大編號(hào)為1-N)起初都在A塔,現(xiàn)要將N個(gè)盤(pán)全部移動(dòng)到C塔(按照河內(nèi)塔規(guī)則),求最少移動(dòng)次數(shù)以及每次的移動(dòng)詳細(xì)情況。

要求:

需要采用遞歸方法和消除尾遞歸兩種方法編寫(xiě)。

盤(pán)數(shù)N由用戶從標(biāo)準(zhǔn)輸入讀入,以一個(gè)整數(shù)表示,然后請(qǐng)調(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)行過(guò)程:"<<endl;
  move(count);
  cout<<"消除尾遞歸方法運(yùn)行過(guò)程:"<<endl;
  move_without_recursion(count);
return 0;
}


如有疑問(wèn)請(qǐng)留言或者到本站社區(qū)交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!

相關(guān)文章

最新評(píng)論