Four pillars strengthened version of the Hanoitower----is sweet or trouble _ four pillars Hanoitower

Source: Internet
Author: User
Tags pow

I think a lot of people may give examples of Hanoi when they first learn recursion, teachers or books.

But today, the focus of our discussion is not the simple Hanoi algorithm, but the extension of the three-column Hanoi. Let's take a look at the classic three-column Hanoi.

One or three column Hanoi (Hanoi_three):

I think we have a good understanding of the three-column Hanoi and the implementation of the algorithm should be very skilled.

I'm here to simply go over it. Three column Hanoi algorithm thought:

There are three pillars of a, B and C, there are n plates on column A, now you need to transfer all the plates on a to C, please give the steps to minimize the number of moves.

Algorithm idea:

1, n-1 a plate to C for the cache, all transferred to column B.

2, will be left on a the nth plate, directly transferred to the C pillar.

3, the n-1 on the B plate, to a for the cache, all transferred to the C column.

It is easy to get the recursive equation of the algorithm: T (n) =2*t (n-1) +1, it is not difficult to calculate the number of steps is t (n) =2^n-1.

The specific code is as follows: [cpp]  view plain copy void move ( char x, char y )    {        printf ("%c --> %c\n",  x, y);  //Print Path,x-->y   }      void hanoi_three ( int n, char a, char b,  char c )    {       if ( n <= 0 )            return ;                  step++;     //Steps +1               if ( n == 1 )        {           move ( a, c  )    //a plate on column A to move directly to column C            return  ;           }       else        {           hanoi_three (  N-1,&NBSP;A,&NBSP;C,&NBSP;B)      //to n-1 a tray on a C as a buffer, all transferred to the  b  column            move ( a, c );                    //the nth plate left on a, directly to  c.    post            hanoi_three ( n-1, b,  A,&NBSP;C)      //the n-1 plate on B to a as a cache, all transferred to  c  column         }  }  


Two or four column Hanoi (Hanoi_four):

When the post is four, for the purpose of simply transferring the plate to another pillar, the difficulty is greatly reduced, and the complexity of the algorithm is greatly reduced. However, this time, if you want to find an optimal, least-step implementation method, it can be said that the difficulty is to promote an order of magnitude.

Some people may question why, my idea of Hanoi with three pillars is not very optimized.

Don't worry, let me slowly come to you.

Let's take a look at this ' seemingly reasonable ' solution:

Suppose, a,b,c,d, respectively: source location, cache, cache, destination location.

Because of the three columns, we put the first n-1 plate of a on the B cache, and then put the nth plate on the C column.

Now the situation is much better, there are two can cache the pillars, so it looks more convenient to move, the original B on the need to cache the N-1 plate, now can just n-2 a plate, and the first n-1 tray on the C cache.

The specific process is as follows (non-optimal solution):

1, from a with the help of C, d the n-2 plate moved to B.

2. Move the first n-1 plate to C.

3, move the nth plate to D.

4, move the first n-1 plate to D.

5, from B to the use of a, C will n-2 plate all moved to D.

Looks, very perfect, the author also once felt that this idea has no flaw, even I thought that found the K-pillar Hanoi general method (take for granted the number of cache on column B from N-2 to n (k-2) plate). Until I read this article: Multi-column Hanoi optimal algorithm design research.

Although we think of making the plates as little overlap as possible to ensure that the minimum number of steps, but this is not absolutely guaranteed. It may be possible to have fewer plates, but when the plates increase, the extra columns that have only one plate can be used (and the possible optimizations are here). While doing so adds up the number of moves per step, but reduces the number of recursion from the other side, we need to find a balance from here.

Let's take a look at the 1941, the United States of J. S. Frame, given the idea of the four-column Hanoi algorithm, also known as the Frame algorithm:

1, using the 4-column Hanoi algorithm, the n-r plates on a column are moved to the B-column "F (n-r) step" through C-Pillar and D-column.

2, using the 3-column Hanoi classical algorithm, the remaining R plate on column A is moved through the C column to the "2^r-1 step" on the D column (refer to the case of the three columns mentioned above).

3, using the 4-column Hanoi algorithm, the n-r plate on the B-pillar is moved through a and C columns to the "F (n-r)" Step on the D column.

4, according to the top rule to find all r (1≤r≤n) in the case of step f (n), the minimum is worth the final solution.

So the recursive equation for the frame algorithm is as follows:

F (n) =min (2*f (n-r) +2^r-1), (1≤r≤n).

Have we found that, in fact, this algorithm is basically the same as we thought the algorithm is reasonable, the difference is that he is the n-2 of our plates to B, instead of the N-r plate transferred to the B column.

Even if the core, the core of the algorithm, is the calculation of n-plate case, r why value, can make the algorithm optimal.

To find the core, our task now is clear, that is, the calculation of R value.

Here is a stupid way to enumerate (don't know if you have any other way). is to bring all the values of N and R in a certain range, and get the value of r that satisfies the minimum value of f (n), recorded as k[n] = R;

The specific code is as follows: [cpp]  view plain copy void init_k (void )    {        int i, k;          __int64 temp;           __int64 m[Max+1] = {0};                    for ( i = 1; i <=  Max; i++ )        {            m[i] = INT_MAX;                 for ( k = 1; k <= i; k++ )             {                temp = 2*m[i-k] +  (__int64) Pow (2,k)  - 1;                    if ( temp <  m[i] )                {                    m[i]  = temp;                        K[i] = k;                       //printf ("K[%d] = %d,  m[i] = %d\n ", i, k, temp );                   }            }       }  }  


After getting the r of each n, the algorithm will become very simple, and the implementation is as follows: [cpp]  view plain copy #include  <stdio.h>   #include   <math.h>   #define  Max 100    #define  INT_MAX  0xfffffffffffffff   int k[max+1] = {0};    int step = 0;          Void hanoi_four ( int n, char a, char  b, char c, char d );      Void hanoi_three (  int n, char a, char b, char c );     Void Move ( char x, char y );          void move (  char x, char y )    {       printf ("%c -- > %c\n ",  x, y);  //print path,x-->y  }      void hanoi_ Three (&NBSP;INT&Nbsp;n, char a, char b, char c )    {        if ( n <= 0 )            return  ;                  step++;      //Steps +1              if ( n == 1 )        {            move ( a, c )    //a plate on column A to move directly to column C             return ;           }        else       {            hanoi_three ( n-1, a, c, b);      // N-1 a plate on aWith C as cache, all transferred to  b  column            move ( a, c  );                    //the nth plate left on a, directly to the  C   column             hanoi_three ( n-1, b, a, c),      //the n-1 plate on B, and a as the cache, all transferred to  c  column        }  }      void hanoi_four (  int n, char a, char b, char c, char d )    {        if ( n <= 0 )             return ;                  if ( n == 1 )        {           step++;            move (  a, d );              return  ;           }       else        {           int kn  = K[n];             //printf ("kn =  %d\n ",  k[n]);                Hanoi_four ( n-kn, a, c, d, b )      //using the 4-column Hanoi algorithm to put a column on the part of N- &NBSP;KN plates are moved through columns C and D to column B            hanoi_three ( kn,  a, c, d );          // Using the 3 column Hanoi classical algorithm, the remaining KN plate on column A is moved through C column to D column.            hanoi_four ( n-kn, b, a, c, d );      //a 4-column Hanoi algorithm to move the N-R plate on column B through column A and C to column D        }   }      void init_k (void )    {        int i, k;          __int64 temp;           __int64 m[Max+1] = {0};                    for ( i = 1; i <=  Max; i++ )        {            m[i] = INT_MAX;                 for ( k = 1; k <= i; k++ )             {                temp = 2*m[i-k] +  (__int64) Pow (2,k)  - 1;                    if ( temp <  m[i] )                {                    m[i]  = temp;                        K[i] = k;                       //printf ("K[%d] = %d,  m[i] = %d\n ", i, k, temp );                   }           }       }  }      int main ()    {        int n;         init_k ();              printf ("please enter the number of the  plates: \n ");       while ( scanf ("%d ",  &n)  !=  eof )        {            step = 0;              hanoi_four (  n,  ' A ',  ' B ',  ' C ',  ' D '  );                //hanoi_three ( n,  ' A ',  ' B ',  ' C '  );      &NBSP;&Nbsp;      printf ("**************************\ntotal step: %d\n",  step );                printf ("please  enter the number of the plates: \n ");       }               return 0;      }  

Here, the four-column Hanoi algorithm is basically finished.

Interested students, you can continue to summarize the implementation of Hanoi column, welcome the exchange of guidance.

Many times, seemingly reasonable behind, is actually a kind of thinking set ...

from:http://blog.csdn.net/cyh_24/article/details/8075578

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.