递归系列之一_南诺塔问题
生活随笔
收集整理的這篇文章主要介紹了
递归系列之一_南诺塔问题
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一、遞歸
程序調用自身的編程技巧稱為遞歸。
構成遞歸需具備的條件:
1. 子問題須與原始問題做相同的事,且更為簡單(往往表現成規模更小);
2. 不能無限制地調用本身,須有個出口,化簡為非遞歸狀況處理。
二、經典漢諾塔問題(Tower of Hanoi)
注:漢諾塔問題介紹和以下圖片均來自百度
漢諾塔(又稱河內塔)問題是源于印度一個古老傳說的益智玩具。大梵天創造世界的時候做了三根金剛石柱子,在一根柱子上從下往上按照大小順序摞著64片黃金圓盤。大梵天命令婆羅門把圓盤從下面開始按大小順序重新擺放在另一根柱子上。并且規定,在小圓盤上不能放大圓盤,在三根柱子之間一次只能移動一個圓盤。
? ? ? ??
例如,初始有3個柱子的漢諾塔問題的移動過程如下:
?
? ? ? ? ? ?
遞歸過程:
? (1)把最左柱子上的(n-1)個盤子借助中間的柱子移到最右的柱子。
?? (2)把最左柱子上第n個盤子移動最右的柱子。
?? (3)把中間的柱子上(n-1)個盤子借助最左柱子移動最右的柱子。
顯然,第(3)步就是一個更小規模的漢諾塔問題,遞歸思維在這里體現的很明顯。
?
C++代碼實現:
1 /* 2 Problem; 3 Tower of Hanoi 4 5 Question Description: 6 there are 3 poles and n plates,all of them on the leftmost pole at first,in this question. 7 all of the plates have different sizes and a larger one is piled up on a smaller one. 8 What you are expected to solve is how to move these plates from the leftmost pole to the rightmost 9 one through a series of steps. In each step you can just move the top plate from one pole to the 10 top of another pole and each smaller plate cann't be pile up on a bigger one. 11 12 Solution: 13 step1: move all of the n-1 plates from the leftmost pole to the middle pole; 14 step2: move the n-th plate from the leftmost pole to the rightmost pole; 15 step3: move the n-1 plates from the middle pole to the rightmost pole; 16 17 obviously, step3 is a recursion of this question with a smaller scale. 18 */ 19 20 /* 21 source code 22 */ 23 #include<iostream> 24 #include<vector> 25 using namespace std; 26 27 struct Pole{ 28 vector<int> plates;//used for storing the plates 29 }Pleft,Pmiddle,Pright; 30 31 void move(Pole &sou,Pole &des){//move the top plate from sou to des 32 if(des.plates.size()==0){ 33 des.plates.push_back(sou.plates[0]); 34 } 35 else{ 36 des.plates.insert(des.plates.begin(),sou.plates[0]); 37 } 38 sou.plates.erase(sou.plates.begin()); 39 } 40 void TOH(int n,Pole &left,Pole &middle,Pole &right){//recursion function 41 if(n==0) return; 42 TOH(n-1,left,right,middle); 43 move(left,right); 44 TOH(n-1,middle,left,right); 45 } 46 47 void print(Pole p){// print the numbers of plates of the Pole p 48 cout<<"numbers of Plates of the Pole:"; 49 int i=0,n=p.plates.size(); 50 for(;i<n;i++){ 51 cout<<p.plates[i]<<" "; 52 } 53 cout<<endl; 54 } 55 56 int main(){ 57 int n;// the quantity of the plate 58 cin>>n; 59 for(int i=0;i<n;i++){ 60 Pleft.plates.push_back(i+1);// initiation 61 } 62 TOH(n,Pleft,Pmiddle,Pright); 63 64 print(Pleft); 65 print(Pmiddle); 66 print(Pright); 67 } View Code?
?
?
?
轉載于:https://www.cnblogs.com/Hazel-97/p/8783417.html
總結
以上是生活随笔為你收集整理的递归系列之一_南诺塔问题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: springmvc.xml 中 url-
- 下一篇: 总结了一下Ubuntu常用命令