TopPowersTowers of Hanoi

Towers of Hanoi

The Towers of Hanoi puzzle is reputed have arisen from a story about a group of buddhist monks in the Tower of Brahma. In the monastery were 3 diamond-tipped needles which were supported vertically. On the first of the diamond-tipped needles were 64 golden disks, arranged in order of size so that the largest was on the bottom. The monks were reputedly given the task of moving the 64 golden disks from the first to the third golden-tipped needle. Making the problem a bit more complicated were the restrictions that only one disk can be moved at a time from one needle to another (no disk may just be set aside) and that it is never allowable to put a large disk on a smaller one.

One can buy a children's puzzle built upon this basis, though they are typically made of plastic or wood and typically only come with 8 or fewer disks (for reasons that will become apparent later).

There is a Towers of Hanoi demo.

The solution to the puzzle is to think recursively. To move n disks from the first needle to the last needle using a helper needle:

  1. If there is only one disk to move, move it from the first to last needle, and you are done.
  2. Otherwise move the top n-1 disks from the first needle to the helper needle (following the rules, of course).
  3. Then move the bottom disk from the first to the last needle.
  4. Then move the top n-1 disks from the helping to the last needle (following the rules, of course).

Here is the key method:

    public void recHanoi (int numDisks, int first, int last, int helper)
    {
        if (numDisks == 1)
        {
            moveDisk(numDisks, first, last);
        }
        else
        {
            recHanoi(numDisks - 1, first, helper, last);
            moveDisk(numDisks, first, last);
            recHanoi(numDisks - 1, helper, last, first);
        }
    }

More details on this puzzle are available in the text.


TopPowersTowers of Hanoi