Tower of Hanoi
Move n disks from peg A to peg C, one at a time and never a larger disk on a smaller one; exactly 2ⁿ − 1 moves.
To move k disks from the source peg to the goal:
- Time:
O(2ⁿ) - Space:
O(n) - Grimaldi, chapter 10
- Johnsonbaugh, chapter 4
Three disks: 7 moves.
def hanoi(n):pegs = {"A": list(range(n, 0, -1)), "B": [], "C": []}moves = []solve(n, "A", "C", "B", pegs, moves)return movesdef solve(k, src, dst, via, pegs, moves):if k == 0:returnsolve(k - 1, src, via, dst, pegs, moves)disk = pegs[src].pop()pegs[dst].append(disk)moves.append((disk, src, dst))solve(k - 1, via, dst, src, pegs, moves)
Start
pegs—
The table is still empty.
Recursion tree
Filled orange = running call · Orange outline = still on the stack · Grey = finished
Local variables
n3
Orange = changed in this step
Call stack
- hanoi()line 1
Step 1 of 78
Explanation
The idea
To move k disks from the source peg to the goal:
- move the top
k − 1disks (recursively) to the spare peg; - move the largest disk to the goal;
- move those
k − 1disks (recursively) from the spare peg on top of it.
How many moves?
T(k) = 2·T(k−1) + 1 and T(0) = 0, so T(n) = 2ⁿ − 1. No fewer are possible: the largest disk must move at least
once, and before that all the others must be out of the way.
What to watch in the trace
- The
pegscard shows the three pegs (bottom to top) and the table lists all moves so far. - The call tree is a complete binary tree of depth
n. - Disk 1 moves on every other move.