Now imagine there are 3 stakes on a plate. The leftmost stake has n plates stacked from small to large. Now you need to move these plates to the rightmost stake as they are, but there are 3 conditions:
First, the conclusion: moving n plates requires 2^n - 1 times.
In this example, the number of plates is set to 3, because it is easier to explain than the larger Tower of Hanoi, but the same concept is used.
→ We use A, B, and C to represent the stakes, and the plates are 1, 2, and 3 from top to bottom.
public class Hanoi {
static void hanoitower(int n,char a,char b,char c){
if(n==1){
System.out.println("移動盤"+n+": " +"從" + a +"到"+ c);
}
else{
hanoitower(n-1,a,c,b);
System.out.println("移動盤"+n+": " +"從" + a +"到"+ c);
hanoitower(n-1,b,a,c);
}
}
public static void main(String[] args) {
int plantNum = 3;
hanoitower(plantNum,'A','B','C');
}
}
Step 1: We are entering a Hanoi Tower with a total of 3 plates. The recursive part will always appear inside else. When n = 1 at the end, it means that plate 1 is moved to column C, and then it will return to the original calling place (line 7), and then the second plate is moved to column B (line 8). Line 9 is passed in as an argument by hanoi(2,A,C,B), and finally the first plate is moved from C to B.
Step 2: At this point, because the third plate we started with has not yet been returned, it returns to line 8 and prints it. Then, from this point on, it continuously recurses from line 9 until it finally returns a void value and the function ends.
(Source)
This video is one that I thought explained very clearly when I was teaching myself Hanoi Towers at the beginning!!! (The grammar part can be ignored, just listen to the analysis)
This is an online visualization tool that supports different programming languages. You can copy the sample program provided above here, and you can understand how Hanoi Towers recursion works step by step in the space next to it.