Explore the Tower of Hanoi algorithm

Explore the Tower of Hanoi algorithm
1, the nature of the problem
HANOR from Indian legend, Brahma created the world as early as the three diamond pillars, which stack a pillar from the bottom up with 64 gold discs. Brahma Brahman command to the disk in order of size from the bottom again placed on the other pillars. Predetermined and can not be amplified in the small-disc, a disc can only be moved between the three pillars.
2. Analysis
(1) First we set these three columns is a column, b columns, column C, as shown in a.
Figure I
(2) Our main goal is to have all the plates a column c is moved to column during the transfer operation, we must ensure that the small cap market below, and can only be moved a disc, the last column c there are all on the plate and also from top to bottom in ascending order.
(3) First, if we want a column plates are moved to c column, it must first maximum of the first plate into the c column, so our first step is you want in addition to the largest of all the dishes plate all move b column.
(4) Then we can be a column as a reference post, b pillar is our goal posts, but the Tower of Hanoi provisions must ensure that the child to be in the small cap market below, so we need to use this time as a pillar a temporary storage place, column c is the most appropriate choice, after some movement, Figure 2, a successful move to the column c largest plate column.
Figure II
(5) Next, all the plates are moved to the b-pillar column c, b-pillar suddenly becomes a reference column, and c columns become the target of the column, we will move to the column by means of a dish. Finally, we will be successful in accordance with the rules and all the plates move to column c, Figure III.
Figure III
...

#include<iostream>
using namespace std;                          //实验对象是n个盘子

void move(char src,char dest)
{
    cout<<src<<"-->"<<dest<<endl;
}

void hanoi(int n,char src,char mediun,char dest)
{                                     
    if(n==1)
        move(src,dest);
    else
    {
        hanoi(n-1,src,dest,medium);         //将a柱上的n-1个盘子移动到b柱
        move(src,dest);                     //将a柱上最大的盘子移动到c柱
        hanoi(n-1,medium,src,dest);         //将b柱上的n-1个盘子移动到c柱
    }
}

int main()
{
    int m;
    cout<<"Enter the number of diskesL";
    cin>>m;
    cout<<"the steps to moving"<<m<<"diskes:"<<endl;
    hanoi(m,'A','B','C');
    return 0;
}

...
I simply use three plates to achieve specific process Tower of Hanoi, as four
Figure IV
3 summarizes
our main use recursion to solve the Tower of Hanoi manner, the key lies in the recursive algorithm recursively repeating steps recursion is then repeated in a key step that good recursive code readability, and embodies the beauty of mathematics.

Guess you like

Origin www.cnblogs.com/xlog/p/11502988.html