Solution to the tower of Hanoi Problem

Source: Internet
Author: User

Set the three plates to A, B, and C;

The recursion method is very simple. When the number of plates is 1, you can directly put the plate on disk A to disk C.

If the number of plates on disk A is N, n-1-1 plates above to disk B, and use disk C as a temporary place;

Then move a plate on drive a to drive C;

Then, move the n-1 plates on disk B to disk C, and use disk A as a temporary disk.

 

CodeAs follows:

# Include <iostream> Using   Namespace  STD;  Void Move ( Int A_n, Int & O_countnum, Char A_a, Char A_ B, Char A_c );  Int  Main (){  Char A = '  A  '  ;  Char B = '  B  '  ;  Char C = '  C  ' ;  Int Countnum = 0  ;  Int  N; cout < "  ==== Hanoi Problem Solving ===\ n  " < "  Enter the number of plates (enter-1 to exit ):  "  ; CIN > N;  While (N! =-1  ) {Move (n, countnum, A, B, C); cout < "  Enter the number of plates (enter-1 to exit ):  "  ; CIN > N ;}  Return   0  ;}  Void Move ( Int A_n, Int & O_countnum, Char A_a,Char A_ B, Char  A_c ){  If ( 1 = A_n) {o_countnum ++ ; Cout <O_countnum < "  : Move the top plate from  " <A_a < "  Move  " <A_c <Endl ;}  Else  {Move (a_n - 1  , O_countnum, a_a, a_c, a_ B); move (  1  , O_countnum, a_a, a_ B, a_c); move (a_n - 1  , O_countnum, a_ B, a_a, a_c );}} 

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.