Every day, an algorithm (the tower of Hanoi) is reviewed.

Source: Internet
Author: User

If the column is marked as ABC, it will be moved from A to C. When there is only one plate, it will be moved directly to C. When there are two plates, B will be treated as the auxiliary column. If there are more than two disks, it is very easy to cover the third and lower plates. Each time we handle two plates, that is: a-> B, A-> C, B-> C, and the hidden part is actually the progressive processing of the program. In fact, if there are n plates, the number of times required for moving is 2 ^ n-1.


# Include <iostream>
# Include <cmath>
# Include <ctime>
Using namespace std;
// Use RAND_MAX

Void hanni (int n, char A, char B, char C)
{
If (n <0)
{
Cout <"n <0" <endl;
Exit (0 );
}
Else
{
If (1 = n)
{
Printf ("moving % d from % c to % c", A, n, C );
Cout <endl;
}
Else
{
Hanni (n-1, A, C, B );
Hanni (1, A, B, C );
Hanni (n-1, B, A, C );
}
}
};
Int main (){
Char A = 'a ';
Char B = 'B ';
Char C = 'C ';
Hanni (3, A, B, C );
Return 0;
}


 

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.