Theory;
Hanoi Tower:
1. There are three poles A, B, and C. There are several dishes on pole a. 2. Move one dish at a time. small dishes can only be stacked on the large one. 3. Move all the dishes from pole a to pole C:
Set a to have n plates.
If n = 1, the disc is directly moved from A to C.
If n = 2, then:
1. Move N-1 (equal to 1) disks on A to B;
2. Move a disc on A to C;
3. Finally, move N-1 (equal to 1) disks on B
If n = 3, then:
A. Move N-1 (equal to 2) disc on A to B (with the help of C) as follows:
(1) Move the n '-1 (equal to 1) disc on A to C.
(2) Move a disc on A to B.
(3) Move the n '-1 (equal to 1) disc on C to B.
B. Move a disc on A to C.
C. Move N-1 (equal to 2, to n ') disks on B to C (with the help of a) as follows:
(1) Move the n '-1 (equal to 1) disc on B to.
(2) Move a plate on B to C.
(3) Move the n '-1 (equal to 1) disc on A to C.
At this point, the movement of the three disks has been completed.
The above analysis shows that when n is greater than or equal to 2, the moving process can be divided into three steps:
Step 1 move the n-1 disc on A to B;
Step 2 move a disc on A to C;
Step 3: Move n-1 disks on B to C;
Obviously, this is a recursive process. The algorithm is programmable as follows:
Package classic; public class HANOI tower {// 2 (a B C)-(a-c) // 1-B // 2-C // 1-C // 3 (a B c)-(a-c) /// the first two disks 2 (a B C) -(a-B) // The third Disk (a B c)-(a-c) // The first two disks (B a c)-(B-C) public static void Hanoi (int n, char origin, char assist, char destination) {If (n = 1) {move (origin, destination);} else {Hanoi (n-1, origin, destination, assist); move (origin, destination); Hanoi (n-1, assist, origin, destination) ;}} public static void move (char origin, char destination) {system. out. println ("move from" + origin + "to" + Destination);}/*** @ Param ARGs */public static void main (string [] ARGs) {// todo auto-generated method stub Hanoi (3, 'A', 'B', 'C ');}}
Hanoi (Hanoi)