This is for the Tower of Hanoi solution as presented in Geeks for Geeks
I am really struggling to understand HOW is this working. I understand their main idea about breaking it down in "Simpler" operations, but I have no idea how the code itself is working.
// Java recursive program to solve tower of hanoi puzzle
class GFG
{
// Java recursive function to solve tower of hanoi puzzle
static void towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod)
{
1 if (n == 1)
2 {
3 System.out.println("Move disk 1 from rod " + from_rod + " to rod " + to_rod);
4 return;
5 }
6 towerOfHanoi(n-1, from_rod, aux_rod, to_rod);
7 System.out.println("Move disk " + n + " from rod " + from_rod + " to rod " + to_rod);
8 towerOfHanoi(n-1, aux_rod, to_rod, from_rod);
}
// Driver method
public static void main(String args[])
{
int n = 4; // Number of disks
towerOfHanoi(n, 'A', 'C', 'B'); // A, B and C are names of rods
}
}
I'm adding those numbers to count the lines for easier reading.
First, the if statement in line 1. That should only execute when n == 1, and it should move the smallest disk from rod A to rod C. After that, line 2, it should return, signifying the end of the recursive method. The problem I have with this code is that moving the smallest disk from rod A to rod C is not only the final step to the algorithm, but also the first one. So how is the algorithm continuing when it's basically saying it should end in the first move?
My next questions are related to the other 2 recursive calls. After that if statement, the function is called again in line 6, but with n-1. So if n is 4, then it should call it with 3
But, what happens when it's called with 3? It should then go back to that if statement and since it's not 1, it should go back to line 6 and now call it with 2, which will continue until it's 1, executing the if block and leading out of the method
So how are the lines 7 and 8 being reached? How can this solution go back to higher numbers once it already decreased them? I mean, if n is 4 and becomes 3, how does it go back to 4 to rearrange that largest disk?
Edit: The suggested, related solution does not answer my specific questions. I already read through it and I'm still left with the same doubts.