Recursion (hanoid Tower)

Source: Internet
Author: User
Question: The Tower of Hanoi (Hong Kong and Taiwan: Hanoi) is a mathematical problem based on a Legend: There are 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 must follow the above two rules. Q: How to migrate data? How many times does it need to be moved at least? Answer: (C #) namespace hanoi_tower {class program {static void main (string [] ARGs) {console. writeline ("Please insert a positive integer:"); string a = console. readline (); int n = convert. toint32 (a); int COUNT = 0; program step = new program (); Count = step. hanoi ('A', 'B', 'C', N, count); console. writeline (count); console. readkey ();} public int Hanoi (char a, char B, char C, int N, int count) {If (n = 1 ){ Console. writeline ("Move disk {0} from {1} to {2 }. ", n, a, c); return 1;} else {COUNT = Hanoi (A, C, B, n-1, count); console. writeline ("Move disk {0} from {1} to {2}", n, a, c); count + = 1; count + = Hanoi (B,, c, n-1, count) ;}return count ;}}note: 1. the returned value type of Readline () is string and needs to be converted to the required type. Method: String STR = console. readline (); // read a row of int A = convert. toint32 (STR); // The first conversion method int B = int. parse (STR); // The Second Conversion Method int C; Int. tryparse (STR, out C); // The third conversion method 2. create an instance of the class to reference the method. 3. Recursive initialization. 4. Q: Can the value obtained by Count be returned to the function in time?

Recursion (hanoid Tower)

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.