About Tower of Hanoi problem

First, Origin:

Tower of Hanoi: Tower of Hanoi (also known as the Tower of Hanoi) problem stems from an ancient Indian legend of educational toys. When Brahma created the world to do three diamond pillars, from the bottom up pile with 64 gold discs in order of size to a post. Brahma Brahman command to the disk in order of size from the bottom again placed on the other pillars. And predetermined, the disc can not be enlarged in a small disk, a disk can only be moved between the three pillars.

The problem stems from the Tower of Hanoi recursive algorithm, it seems very simple, like a lot of trouble, to deeply understand the true meaning of recursion, all the discs on the first pillar all get on the third plate, in fact, these plates can abstract divided into two parts, the bottom of the platter, and the top small plates.

 

All plates from column A to column B moves

(1) when N = 1, only one plate, one only needs to move: A-> l-> B;
(2) when N = 2, it is necessary to move three times:
        A-> l-> C

        A —>2—>B

        C -> l-> B
(. 3) if N = 3, the moving step is specifically:

       A—>1—> B,    A —>2—>C,    B —>1—>C.       (3.1)

       A—>3—>B.                                                         (3.2)

       C—>1—>A,    C —>2—>B,    A —>1—>B.         (3.3)

 Three plates come view, the smallest first plate on a third column, and then to the second plate on the two pillars, and the smallest on the second, the bottommost you can now get on the third column, followed by the smallest plate on the second column on a first column, the second small plate on top of the bottom most plate in the third column, and then the smallest in the third pillar above, we will

Three pillars named 'A', 'B', 'C'; we are to find ways to help 'C' pillars, above the very bottom of all the dishes on the 'B', then these plates by means of 'C' pillar place in the 'a' pillar, thus completed the Tower of Hanoi, is the following code shows:

void han(char A,char  B,char C,int n){
        if(n<=1){
                  printf("%c->%c",A,C);
                   return;
                   }
         han(A,C,B,n-1);
         printf("%c->%c",A,C);
         han(B,C,A,n-1);  
        
}             

 If you have questions, ideas and comments are welcome below ~

Guess you like

Origin www.cnblogs.com/julyzqy/p/11730192.html