next up previous
Next: Number of activations in Up: Unit 11 Previous: Multiple recursion

Example: Towers of Hanoi

The problem of the Towers of Hanoi originates from an ancient legend from Vietnam, according to which a group of monks is moving around a tower of 64 disks of different sizes according to certain rules. The legend says that, when the monks will have finished moving around the disks, the end of the world will come. The rules according to which the disks have to be moved are the following:

The initial state (a), an intermediate state (b), and the final state (c) for a set of 6 disks are shown in the following figures:

(a)        \includegraphics{figures/fig-11-01-hanoi-ini.eps}

(b)        \includegraphics{figures/fig-11-02-hanoi-int.eps}

(c)        \includegraphics{figures/fig-11-03-hanoi-fin.eps}

We want to realize a program that prints the sequence of moves to be done. For each move we want to print a statement as follows (where x and y are either 1, 2, or 3):

move a disk from support x to support y

Idea: to move n > 1 disks from support 1 to support 2, using 3 as auxiliary support:

  1. move n - 1 disks from 1 to 3 (without moving the n-th disk)
  2. move the l'n-th disk from 1 to 2
  3. move n - 1 disk from 3 to 2 (without moving the n-th disk)

Implementation (this is another example of multiple recursion):

import javax.swing.JOptionPane;

public class Hanoi {

  private static void moveADisk(int source, int dest) {
    System.out.println("move a disk from " + source + " to " + dest);
  }

  private static void move(int n, int source, int dest, int aux) {
    if (n == 1)
      moveADisk(source, dest);
    else {
      move(n-1, source, aux, dest);
      moveADisk(source, dest);
      move(n-1, aux, dest, source);
    }
  }

  public static void main (String[] args) {
    int n = Integer.parseInt(
      JOptionPane.showInputDialog("How many disks do you want to move?"));
    System.out.println("To move " + n +
                       " disks from 1 to 2 using 3 as auxiliary disk:");
    move(n, 1, 2, 3);
    System.exit(0);
  }
}


next up previous
Next: Number of activations in Up: Unit 11 Previous: Multiple recursion