When the number of plates is two, move the chart as follows:
The law of movement is:
| Steps |
Plate number |
SOURCE Pillars |
Target Pillar |
| 1 |
1
|
A |
B |
| 2 |
2 |
A |
C |
| 3 |
1 |
B |
C |
When the number of plates is 3:
The law of movement is:
| Steps |
Plate number |
SOURCE Pillars |
Target Pillar |
| 1 |
1 |
A |
C |
| 2 |
2 |
A |
B |
| 3 |
1 |
C |
B |
| 4 |
3 |
A |
C |
| 5 |
1 |
B |
A |
| 6 |
2 |
B |
C |
| 7 |
1 |
A |
C |
Moving from the above rule can be summed up, when the number of steps and plates in the same time, is the bottom of the plate from A to C, the other steps are equivalent, the law is as follows:
The above actions are: the source pillar (A) is unchanged, the target column is C, the auxiliary pillar is b to move, that is
Target pillars, source pillars
Auxiliary pillars, source pillars
Auxiliary pillars, Target pillars
Intermediate action: from a to C i.e. from the source column to the target pillar
The following action: The source column is B, the target column is C, the auxiliary pillar is a move, which is
Auxiliary pillars , source pillars
target pillars , source pillars
Auxiliary Pillars -- target pillars
According to the above rules, you can probably summarize the actual movement of the main action is actually repeating the three-step action, with Java code can be expressed as follows:
/** * @author lenovo * */public class hanoi { / ** * * @param n number of plates * @param origin Source blocks * @param assist Ancillary blocks * @param destination Destination seat */ public void hanoi (int n, char origin, char assist, char destination) { if (n >= 1) { hanoi (n - 1, origin, destination, assist); system.out.println ("Direction:" + origin + "--->" + destination); hanoi (n - 1, assist, origin, destination); } } public&nbsP;static void main (String[] args) { hanoi hanoi = new hanoi (); hanoi.hanoi (3, ' A ', ' B ', ' C '); }}
At first I understand this algorithm is always in the analysis of the program's stack, into the stack action, after reading this article Hanoi recursive algorithm and analysis just a little, this algorithm is actually test the understanding of recursive thinking: summarize the rules of things, and then use the program to express.
Understanding of the Hanoi algorithm