Story:
It is said that at the time of the creation of the century there was a boro Church which was supported by three diamond rods. At the beginning, God placed 64 gold disks arranged from top to bottom in ascending order on the first rod, and ordered the monks to move all the gold disks from the first stone rod to the third stone rod, and observe the principle that the big plate is under the Small Plate during the handling process. If only one plate is moved every day, when the plate is fully moved, the tower will be damaged, that is, the end of the world.
Solution:
This is a classic RecursionAlgorithm. Mark the three columns as A, B, and C. The problem is that N gold disks are moved from A to C. The principle of large Plates under small plates is observed during the handling process. We marked the gold disk from top to bottom as 1 to n. The problem can be broken down into (1) migrating 1 to n-1 gold disks from A to B, with C as the transition; (2) Moving N from A to C; (3) move the 1-n-1 gold disk from B to C and use a as the transition.
CodeCore:
Public Static Void Haoni ( Int N, Char A, Char B, Char C ){
If(N= 1){
system. out. println ( " NO. " + n + " slice " + A + " move to " + C );
}Else{
//1. Move the 1-n-1 gold disk from A to B and use C as the transition
Haoni (n- 1, A, C, B );
// 2. Move N from A to C
System. Out. println ( " The " + N + " Slice " + A + " Move " + C );
//3. Move the 1-n-1 gold disk from B to C and use a as the transition
Haoni (n- 1, B, A, C );
}
}
All code:
Package Com. icescut. Classic. algorithm;
Public ClassHanoi {
Public Static VoidMain (string [] ARGs ){
haoni ( 4 , ' A ' , ' B ' , ' C ' ); // taking four gold disks as an example
}
Public Static VoidHaoni (IntN,CharA,CharB,CharC ){
If(N= 1){
system. out. println ( " NO. " + n + " slice " + A + " move to " + C );
}Else{
//1. Move the 1-n-1 gold disk from A to B and use C as the transition
Haoni (n- 1, A, C, B );
// 2. Move N from A to C
System. Out. println ( " The " + N + " Slice " + A + " Move " + C );
//3. Move the 1-n-1 gold disk from B to C and use a as the transition
Haoni (n- 1, B, A, C );
}
}
}