C-language refer tower problem, C-language refer Tower

Source: Internet
Author: User

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:


 


Related Article

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.