Tower of Hanoi
[Math, Recursion]
Tower of Hanoi is a mathematical puzzle where we have 3 rods and n disks. The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules:
Only one disk can be moved at a time.
Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack.
No disk may be placed on top of a smaller disk.
Write a program which prints a sequence of operations that move n disks from one rod to another.
Reference: EPI python, page 226
Solution: Recursion
Idea:
Use recursion. Think about if we know how to move the top n-1 disks, how can we move n disks.
Time complexity: because in the recursion we have
Space Complexity:
Last updated