13.6 Programming Activity 2: The Towers of Hanoi

A well-known problem that lends itself to an elegant recursive formulation is the Towers of Hanoi. Here it is:

  • There are three towers, which we can represent as the source tower, the temporary tower, and the destination tower.

  • We have a stack of n disks piled on the source tower; all the disks have a different diameter. The largest disk is at the bottom and the smallest disk is at the top.

  • The goal is to transfer all the disks, one at a time, to the destination tower using all three towers for help. No larger disk can be placed on top of a smaller one.

The recursive solution to the problem for the general case (n >= 1) is as follows:

  1. Transfer the top (n − 1) disks from the source tower to ...

Get Java Illuminated, 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.