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 calledA(source),B(spare) andC(target); disc 1 is the smallest. - Define
hanoi(n, source, target, spare): to movendiscs, first moven - 1discs to the spare rod, then move discnto the target and finally then - 1discs 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).
2
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