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:
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):
Idea: to move n > 1 disks from support 1 to support 2, using 3 as auxiliary support:
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); } }