Lecture 18

  1. Towers of Hanoi

Towers of Hanoi

One of the more interesting uses of recursion comes from an old story:

The Towers of Hanoi puzzle is reputed to 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).

Check out this DEMO of a program to solve the problem.

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:

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);
        }
    }

We can make this a bit more concrete by looking at a specific example:

                                        {recHanoi(1,A,C,B) - Move 1 from A to C
                  {recHanoi(2,A,B,C)    {Move 2 from A to B
                  {                     {recHanoi(1,C,B,A) - Move 1 from C to B
recHanoi(3,A,C,B) {Move 3 from A to C
                  {                     {recHanoi(1,B,A,C) - Move 1 from B to A
                  {recHanoi(2,B,C,A)    {Move 2 from B to C
                                        {recHanoi(1,A,C,B) - Move 1 from A to C

How do we know this will work?

  1. Base case: (one disk) works.
  2. If we assume that it works for n-1 disks, then it will work for n disks.
  3. If we start with a positive number of disks then we will eventually get down to 1 (base case).