# Implementation of Hanoi Tower in Java

Suunsr 2022-05-22 12:25:58 阅读数:55

implementationhanoitowerjava

Hanoi （Tower of Hanoi）, also called Hanoi Tower , It's a puzzle toy originated from an ancient Indian legend . Vatican made three diamond pillars when he created the world , Stack on a column from bottom to top in order of size 64 A golden disk . Brahman ordered Brahman to rearrange the disc from below on another pillar in order of size . And stipulate , You can't enlarge a disc on a small disc , Only one disc can be moved between the three pillars at a time .

The train of thought is ： Hanoi Tower n Disc , First of all, will 1–n-1 Think of a plate as a plate , because n-1 The top plates are better than n-1 Small , So use n-1 Instead of 1–n-1 Move a disk , The movement of only two plates on the tower of Hanoi is A->B,A->C,B->C,n The disk returns to the final position , Yes n-1 The disk is again similar to n Disk operation . until n by 1 until , Recursion ends .

## The demo :

``````public class Test{
public static void main(String[] args) {
int n = 3;
char a = 'A',b = 'B',c = 'C';
hanio(n,a,b,c);
}
public static void hanio(int n,char a, char b, char c){
// When there's only one plate , Directly from A Move to C
if(n == 1){
move(n,a,c);
}else{
// Three steps , observe ,a,b,c The position of the three changes
//1. hold n-1 One plate as a whole , With the help of C from A Move to B
hanio(n-1,a,c,b);
//2. The first n A plate from A Move to C
move(n,a,c);
//3. And then n-1 Plate as a whole , With the help of A from B Move to C
hanio(n-1,b,a,c);
}
}
public static void move(int n , char a, char b){
System.out.println(" The first "+ n +" A plate from "+ a +" Move to "+ b);
}
}
}``````