Tower of Hanoi (for C, Python, or Java)

863 Views Asked by At

I am not fully understanding the Towers of Hanoi. The recursion is very elegant and the answer has eluded me for a very long time. I am currently learning python, so lets use python.

def TowerOfHanoi(n,from_rod, to_rod, aux_rod):
    if n==1:
        print ("Move disk 1 from rod", from_rod, "to rod", to_rod)
        return
    TowerOfHanoi(n-1,from_rod, aux_rod, to_rod)
    print ("Move disk", n, "from rod", from_rod, "to rod", to_rod)
    TowerOfHanoi(n-1,aux_rod, to_rod, from_rod)

n=4
TowerOfHanoi(n,'A', 'C', 'B')]

This is the correct code for the Tower of Hanoi. I understand the two calls within the function. I have drawn a picture that shows the disk moving from from_rod to aux_rod, then the next call moves it from aux_rod to to_rod. That makes sense now.

I do not understand how the function is calling the disks in that order and how the program continues for so long. If you understand the TowersOfHanoi in C, Java, pseudocode, python, or Matlab then your help is greatly appreciated.

1

There are 1 best solutions below

0
On BEST ANSWER

This is the C++ (a very similar language to C) code of Hanoi's Tower:

enter image description here

And here the output for $n=4$:

enter image description here