Tower of Hanoi:
The quanta (also known as Hanoi) problem is originated from an ancient legend of India's educational toys. When I created the world, da fan Tian made three diamond pillars, stacked 64 gold disks from bottom to top in order of size. The great fan Tian command Brahman re-placed the disc from below in order of size on another pillar. It is also stipulated that the disc cannot be enlarged on a small disc, and only one disc can be moved between the three pillars at a time.
The following is a recursive solution:
Code:
1 # include <stdio. h> 2 3 void hanio (int n, Char, Char, char); 4 5 void main () 6 {7 char a = 'A', B = 'B ', C = 'C'; 8 int N; 9 10 while (1) 11 {12 printf ("Enter the number of disks (0 indicates the end ):"); 13 scanf ("% d", & N); 14 hanio (n, a, B, c); 15 printf ("\ n "); 16} 17} 18 19 void hanio (int n, char a, char B, char c) 20 {21 if (n = 1) 22 {23 printf ("moving disk % d from column % C to column % C \ n", n, a, c ); 24} 25 else26 {27 hanio (n-1, A, C, B); 28 printf ("moving disk % d from column % C to column % C \ n ", n, a, c); 29 hanio (n-1, B, A, C); 30} 31}
The second is a non-recursive solution:
Code:
1 # include <iostream> 2 # include <vector> 3 4 using namespace STD; 5 6 class needle 7 {8 Public: Needle () 9 {10. push_back (100); 11} 12 Void push (int n) 13 {14. push_back (n); 15} 16 int top () 17 {18 return. back (); 19} 20 int POP () 21 {22 int n =. back (); 23. pop_back (); 24 return N; 25} 26 int movenum (int n) 27 {28 int I = 1; 29 While (A [I]> N) I ++; 30 return. size ()-I; 31} 32 int size () 33 {34 return A. size (); 35} 36 int operator [] (int n) 37 {38 return a [n]; 39} 40 private: vector <int> A; 41 }; 42 43 void Hanoi (int n) 44 {45 needle [3], ns; 46 int source = 0, target, target_m = 2, disk, M = N; 47 for (INT I = N; I> 0; I --) 48 needle [0]. push (I); 49 while (n) 50 {51 if (! M) 52 {53 source = NS. pop (); 54 target_m = NS. pop (); 55 m = needle [Source]. movenum (NS. pop (); 56} 57 if (M % 2) target = target_m; 58 else target = 3-source-target_m; 59 If (needle [Source]. top () <needle [target]. top () 60 {61 disk = needle [Source]. top (); 62 m --; 63 cout <disk <"move" <(char) (source + 0x41) <"to" <(char) (target + 0x41) <Endl; 64 needle [target]. push (needle [Source]. pop (); 65 if (Disk = N) 66 {67 source = 1-source; 68 target_m = 2; 69 m = -- N; 70} 71} 72 else73 {74 NS. push (needle [Source] [Needle [Source]. size ()-M]); 75 ns. push (target_m); 76 ns. push (source); 77 m = needle [target]. movenum (needle [Source]. top (); 78 target_m = 3-source-target; 79 source = target; 80} 81} 82} 83 84 void main () 85 {86 int N; 87 while (1) 88 {89 cout <"Enter the number of disks (0 indicates the end):"; 90 CIN> N; 91 If (! N) break; 92 Hanoi (n); 93 cout <Endl; 94} 95}
In addition:
Origin: http://baike.baidu.com/view/191666.htm#1
Related legends: http://baike.baidu.com/view/191666.htm#2
Reference: http://baike.baidu.com/view/191666.htm#4_3