progress

~/problems / Backtracking

Tower of Hanoi

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or play this problem's boss fight .

easy ▶ boss game: The Doom Tower 2 levels ~20 min

Level 1 Tower of Hanoi

Deep under the Doom Tower, monks move a stack of golden disks, all different sizes, from peg src to peg dst, using peg via to help. Two rules: move one disk at a time (the top disk of a peg), and never put a bigger disk on a smaller one.

Write hanoi_moves(n: int, src: str, via: str, dst: str) -> list[tuple[str, str]]: the shortest list of moves, each a pair (from_peg, to_peg), that carries all n disks from src to dst.

hanoi_moves(1, "A", "B", "C")   # [("A", "C")]
hanoi_moves(2, "A", "B", "C")   # [("A", "B"), ("A", "C"), ("B", "C")]
hanoi_moves(3, "A", "B", "C")   # [("A", "C"), ("A", "B"), ("C", "B"), ("A", "C"),
                                #  ("B", "A"), ("B", "C"), ("A", "C")]
hanoi_moves(0, "A", "B", "C")   # []
  • 0 <= n <= 20. The shortest solution is unique (2^n - 1 moves), so the tests compare it move by move.
  • ⭐ Bonus: a speed test with 20 disks (about a million moves) earns a star if you make each move once.
Show hint

the biggest disk moves from src to dst exactly once, and at that moment every other disk must be on via. Getting them there is the same puzzle with one disk fewer.

Level 2 unlocks when level 1 passes.

Topic: Recursion and backtracking. Choose, recurse, un-choose: subsets, permutations, N-queens, pruning.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc