Recursion · 12 / 18 Exercise Hard

Towers of Hanoi

Objective

The Towers of Hanoi puzzle has three rods and n discs of different sizes stacked on the first one. They must be moved to the third one, moving one disc at a time and never placing a large one on top of a small one. It is solved with a very short recursion.

Instructions

  • Read n (the number of discs, from 1 to 6). The rods are called A (source), B (spare) and C (target); disc 1 is the smallest.
  • Define hanoi(n, source, target, spare): to move n discs, first move n - 1 discs to the spare rod, then move disc n to the target and finally the n - 1 discs from the spare to the target.
  • Each time a disc is moved, show Move disk d from X to Y.
  • At the end show Total: t, with the total number of moves (2^n - 1).
Input
2
Output
Move disk 1 from A to B
Move disk 2 from A to C
Move disk 1 from B to C
Total: 3

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise