Example 46: Tower of Hanoi

Learn how to solve the Tower of Hanoi problem.

Problem

There are three pegs labeled A, B, and C. Four disks are placed on peg A. Disks decrease in size with the bottom-most disk being the largest and the topmost disk being the smallest.

The objective of the game is to move the disks from peg A to peg C using peg B as an auxiliary peg. The rules of the game are as follows:

  • Only one disk may be moved at a time, and it must be the top disk on one of the pegs.
  • A larger disk should never be placed on top of a smaller disk.

Write a program to print out the sequence in which the disks should be moved such that all disks on peg A are finally transferred to peg C.

Demonstration

Get hands-on with 1400+ tech skills courses.