Miscellaneous problems · Exercise 84 of 100

Solve the Tower of Hanoi

Start with three pegs and a stack of disks ordered from largest at the bottom to smallest at the top. Move one top disk at a time and place it only on an empty peg or a larger disk. To transfer a stack, use the same method to move all but its bottom disk to the spare peg, move the bottom disk to the target, then transfer the smaller stack onto it.

Try it yourself

Use the recursive method to move a stack of four disks from peg A to peg C using peg B. Counting from move 1, on which move does the largest disk leave peg A?

One-step hint

Before the largest disk can move, the top three must reach B. Break that transfer into two transfers of a two-disk stack plus one single-disk move.

Worked solution
  1. One disk takes one move. Two disks take three moves because the small disk moves aside, the larger one moves across, and the small one follows.
  2. Moving the top three disks to B takes 3 + 1 + 3 moves by the same rule. After those seven moves, the largest disk goes directly to C on move 8.
DSA compiler

Explore the idea visually in the recursion lab.