Programming the Tower of Hanoi


The Tower of Hanoi is a puzzle game with three rods and n disks of different sizes which can slide onto any rod. The puzzle starts with the disks stacked in ascending order of size on one rod, the smallest at the top, making a conical shape.

The goal of this puzzle is to move all the disks from the first rod to the last rod while following these rules:

  • You can only move one disk at a time.
  • A move consists of taking the uppermost disk from one of the stacks and placing it on top of another stack.
  • You cannot place a larger disk on top of a smaller disk.

**Write a function that prints out all the steps necessary to complete the Tower of Hanoi. ** In your code, the disks will be numeric values and the rods will be alphabetic with a = first rod, b = middle rod, and c = destination rod.

For example, when n = 3, your output should look like the following:

Moving disk 1 from a to c
Moving disk 2 from a to b
Moving disk 1 from c to b
Moving disk 3 from a to c
Moving disk 1 from b to a
Moving disk 2 from b to c
Moving disk 1 from a to c


Access restricted

Subscribe to premium account to see the solution.

Get premium now