Next: Number of activations in Up: Unit 10 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:

• initially, the disks are placed in decreasing size on support 1
• the objective is to move them to support 2, making also use of an auxiliary support 3;
• the conditions for moving the disks are:
• all disks (except the one to be moved) have to be on one of the three supports;
• it is possible to move only one disk at a time, taking it from the top of the tower on one of the supports and placing it on the top of the tower on another support;
• a disk can never be placed on a smaller disk.

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)

(b)

(c)

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: Number of activations in Up: Unit 10 Previous: Multiple recursion