C-language refer tower problem, C-language refer Tower
// Kailu garji-blog Park Co., http://www.cnblogs.com/kailugaji/.
The Tower consists of three poles, A, B, and C. There are n (n> 1) perforated disks on rod A, and the size of the disks decreases from bottom to top. Move all disks to the C rod according to the following rules: Only one disc can be moved at a time, and the tray cannot be stacked on a small disk. Tip: You can temporarily place the disc on rod B, or move the disc removed from Rod A back to Rod A, but both of them must follow the above two rules. Q: How to migrate data? How many times does it need to be moved at least?
Analysis:
(1) Move n-1 plates on A to B with the help of C;
(2) Move the remaining plate of A to C;
(3) Move n-1 plates on B to C using.
The program implementation is as follows:
1 # include <stdio. h>
2
3 int sum = 0; // global variable
4
5 void move (char x, char y) {
6 printf ("% c --> % c \ n ", x, y);
7 sum = sum + 1;
8}
9
10 int hanoi (int n, char a, char B, char c) {
11 if (n = 1) {
12 move (a, c);
13}
14
15 else {
16 hanoi (n-1, a, c, B);
17 move (a, c);
18 hanoi (n-1, b, a, c);
19}
20}
21 void main () {
22 int m;
23
24 printf ("Please input a number :");
25 scanf ("% d", & m);
26
27 printf ("The step to moving % d disks: \ n", m);
28 hanoi (m, 'A', 'B', 'C');
29 printf ("It need % d steps \ n", sum);
30}
Result: