I have the following working program for tower of Hanoi where we will move disks from A--B tower and C is the extra tower.I defined the initial state of the function as follows: moveDisks(n, 'A', 'B', 'C');
I will print each time I make a move using the following algorithm:
public static void moveDisks(
int n,
char fromTower,
char toTower,
char auxTower)
{
if (n == 1) // Stopping condition
System.out.println(
"Move disk " + n + " from " + fromTower + " to " + toTower);
else
{
moveDisks(n - 1, fromTower, auxTower, toTower);
System.out.println(
"Move disk " + n + " from " + fromTower + " to " + toTower);
moveDisks(n - 1, auxTower, toTower, fromTower);
}
}
}
As you can see from the recursive calls in my program, I have three possible calls:
A--B--C //fromTower, toTower,auxTower
A--C--B //fromTower, auxTower, toTower
C--B--A //auxTower, toTower, fromTower
However, I'm getting the following printouts for 3
disks:
The moves are:
Move disk 1 from A to B
Move disk 2 from A to C
Move disk 1 from B to C
Move disk 3 from A to B
Move disk 1 from C to A
Move disk 2 from C to B
Move disk 1 from A to B
I know my program is correct but I'm not really getting how it's doing B--C
and C--A
calls because I never made such function/method.I would appreciate if you can show how this recursive method is working in terms of three disks using my A--B--C
, fromTower, toTower,auxTower
model.