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;
}