I’ve been really struggling to grasp how this program works.
I’ve read a lot of articles and I still can’t understand, none actually refer to how the program works. I’ll really try to make my questions as clear as possible.
So this is the program
// 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)
{
if (n == 1 )
{
System.out.println( "Move disk 1 from rod " + from_rod + " to rod " + to_rod);
return;
}
towerOfHanoi(n- 1 , from_rod, aux_rod, to_rod);
System.out.println("Move disk "+ n + " from rod " + from_rod + " to rod " + to_rod);
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
}
}
Taken from Geeksforgeeks article on the solution
OK so, I understand the initial call. And I understand that after the return statement, the other calls occur.
What I don’t understand is how is this program not failing? It seems almost like magic to me.
The 2nd call to the method says that its arguments are in a different order from the method’s definition. The method’s definition states that the arguments are FROM, TO and AUX, but the 2nd call says they’re FROM, AUX and TOO.
Is this order affecting the result? Or is the order irrelevant?
Also at one point, the n needs to go back to being its original value, otherwise the program would be unable to move any disk asides from 1. How is this happening? I don’t see any increment operation there. If I run the program through a debugger on my IDE using 3 discs, the value of n sometimes simply goes from 1 to 3 and I have no idea how that can be happening.
It’s a very confusing problem and I’m really tired about reading articles, because none of them actually try to walk you through the code solution.
