Recursive Tower of Hanoi program
def TowerOfHanoi(n , source, destination, via):
if n>=1:
TowerOfHanoi(n-1, source, via, destination)
print("Move disk",n,"from source",source,"to destination",destination )
TowerOfHanoi(n-1, via, destination, source)
Sequence of calls
3 A B C initial call
2 A C B recursive call
1 A B C - recursive call
0 A C B - Nothing happens
-- Prints Move disk 1 from source A to destination B
The recursion has reached its first end
Now, the 2 A C B resumes - Prints Move disk 2 from source A to destination C
1 B C A - Prints Move disk 1 from source B to destination C (ignoring the 0 _ call)
Now the 3 A B C resumes - Prints Move disk 3 from source A to destination B
And this goes on as shown in output below..
TowerOfHanoi(3,"A","B","C")
TowerOfHanoi(3,"A","C","B")
TowerOfHanoi(5,"A","C","B")