Data Structures and Algorithms base of the Tower of Hanoi

  Tower of Hanoi (Tower of Hanoi) from Indian legend, the three magic stone pillars made large Brahma created the world, wherein a column bottom from the stack 64 upwardly gold disk. 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.

Pseudo algorithm (focus on understanding):

. 1  IF (n> . 1 ) {
 2     before the n-1 on the first plate A by means of column C is moved from the A B // key
 3     to the n-th column A on the plate to move directly C // n th is a bottom
 4     and then n-1 on a plate column from B a B moved by C // key 
5 }

 

Three discs: The number of times the mobile plate 7 is

 

Four disks: The number of mobile plate 15

 

Suppose there are n sheets, the number of movements is f (n). Clearly f (1) = 1, f (2) = 3, f (3) = 7, and f (k + 1) = 2 * f (k) + 1. Thereafter difficult to prove f (n) = 2 ^ n-1.

. 1 #include <stdio.h>
 2  
. 3  // shape function parameters A, B, C do not necessarily represent the A, B, C pillars, recursive parameter passing time vary! 
. 4  void hanoit ( int n-, char A, char B, char C) {
 . 5      IF (n-== . 1 ) {
 . 6          // if left a plate, the plate directly on the A pillar to move from A C (from the initial column to a target column) 
. 7          the printf ( " the number% d is moved from the plate column% c% c columns " , n-, a, C);
 . 8      }
 . 9      the else {
 10        // otherwise, first column a n-1 on a plate moves from a by C B (medium to move from an initial column column) 
. 11        hanoit (N- . 1 , a, C, B);// NOTE parameter order: to move from A to B via C 
12 is        
13 is        the printf ( " The number% d is moved from the plate column% c% c columns " , n-, A, C);
 14        
15        // Finally B n-1 on a plate by means of column a is moved from B to C (from the media to the target column column) 
16        hanoit (N- . 1 , B, a, C);
 . 17      }
 18 is  }
 . 19  
20 is  int main () {
 21 is      // three columns a, B, C, respectively, the initial effect of the column, the medium column, the target column 
22 is      char CHl = ' a ' ;
 23 is      char CH2 = ' B ' ;
 24      char CH3 = ' C' ;
 25      
26 is      int n-;
 27      
28      the printf ( " moving plate number: " ); // last of a number plate, the top number is the first dish. 1 
29      Scanf ( " % D " , & n-) ;
 30      
31 is      hanoit (n-, ' A ' , ' B ' , ' C ' );
 32      
33 is      
34 is      return  0 ;
 35 }

 

Guess you like

Origin www.cnblogs.com/sunbr/p/11361433.html