Loading...
Loading...
Loading...
Three pegs A, B and C hold n disks. Move all disks from A to C, one at a time, never putting a bigger disk on a smaller one. Write a recursive function hanoi(n, source, target, spare) that prints each move as Move disk d from X to Y (disk 1 is the smallest), and call it for A, C, B.
Example
Input
2
Output
Move disk 1 from A to B Move disk 2 from A to C Move disk 1 from B to C
Three moves.
Try the problem first. Open one hint at a time.
To move n disks: first move n - 1 disks out of the way, then move the biggest disk, then move the n - 1 disks on top of it.
The base case is n == 0: do nothing.
Write your Python code, run it on the examples and submit it to hidden tests.
Solve in the editor