递归系列之一_南诺塔问题

一、递归

  程序调用自身的编程技巧称为递归。

  构成递归需具备的条件:

    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

 

 

 

 

posted @ 2018-04-11 08:53  Hazel_97  阅读(232)  评论(0编辑  收藏  举报