Fundamental Algorithms Analysis (005)-Hanoi Tower【汉诺塔】

Hanoi Tower

关于汉诺塔的问题描述已经人尽皆知了,在此便不再赘述。汉诺塔问题是一个经典的递归案列。

Hanoi tower recursive method

void hanoi(int plates,vector<int> &A,vector<int> &B,vector<int> &C){
    //position:A->C,B is temporary state
    if(plates==1) (C.push_back(A.back()),A.pop_back());//A->C
    else{
        hanoi(plates-1,A,C,B);//move n-1 plates from to A to B
        hanoi(1,A,B,C);//move the surplus 1 plate(the bottom one) from A to C
        hanoi(plates-1,B,A,C);//move the n-1 plates from B to C
    }
}

Guys can try this version as well. I think they are the same.
别样的边界判定,但其实道理如出一辙。

void hanoi(int plates,vector<int> &A,vector<int> &B,vector<int> &C){   
    if(plates>0){
    	hanoi(plates-1,A,C,B);//move n-1 plates from to A to B
    	(C.push_back(A.back()),A.pop_back());//move from A to C
    	hanoi(plates-1,B,A,C);//move the n-1 plates from B to C
    }
}

Main test

在此,还是简要说明一下该算法的步骤。重点只有一个,每一次先将最下面的盘子处理好。这就不可避免的涉及到先如何将上面其余的盘子处理好,但对于每一摞盘子,都是要先处理好最底下的盘子。依此类推就得到一系列的子过程,有这些子过程一步步可以到达最后的真问题的解。

#include 
#include 
using namespace std;
struct tower{vector<int> A,B,C;};
void hanoi(int plates,vector<int> &A,vector<int> &B,vector<int> &C){
    //position:A->C,B is temporary state
    if(plates==1) (C.push_back(A.back()),A.pop_back());//A->C
    else{
        hanoi(plates-1,A,C,B);//move n-1 plates from to A to B
        hanoi(1,A,B,C);//move the surplus 1 plate(the bottom one) from A to C
        hanoi(plates-1,B,A,C);//move the n-1 plates from B to C
    }
}
int main()
{
    tower t;
    int plates=10,i=plates;
    fill_n(back_inserter(t.A),plates,0);
    while(i>0) t.A[plates-i]=i--;
    hanoi(plates,t.A,t.B,t.C);
    cout<<t.A.size()<<" "<<t.B.size()<<endl;
    for(int j=0;j<t.C.size();++j)cout<<t.C[j]<<" ";
}

建议不要尝试太大的数字,因为可能你的电脑并不能及时算出来。

你可能感兴趣的:(c++,算法)