Easy Tutorial
❮ Java String Concat Java9 Multiresolution Image_Api ❯

Java Example - Tower of Hanoi Algorithm

Java Examples

The Tower of Hanoi (also known as the Riverine Tower) puzzle is a brain teaser derived from an ancient Indian legend. When Brahma created the world, he made three diamond pillars, with 64 golden disks stacked in descending order on one pillar. Brahma commanded the priests to move the disks from the bottom up in order to another pillar. The rules stipulated that a smaller disk could not be placed on a larger one, and only one disk could be moved between the three pillars at a time.

Later, this legend evolved into the Tower of Hanoi game, with the following rules:

The following example demonstrates the implementation of the Tower of Hanoi algorithm:

MainClass.java File

public class MainClass {
    public static void main(String[] args) {
        int nDisks = 3;
        doTowers(nDisks, 'A', 'B', 'C');
    }
    public static void doTowers(int topN, char from, char inter, char to) {
        if (topN == 1){
            System.out.println("Disk 1 from "
            + from + " to " + to);
        }else {
            doTowers(topN - 1, from, to, inter);
            System.out.println("Disk "
            + topN + " from " + from + " to " + to);
            doTowers(topN - 1, inter, from, to);
        }
    }
}

The above code outputs the following result:

Disk 1 from A to C
Disk 2 from A to B
Disk 1 from C to B
Disk 3 from A to C
Disk 1 from B to A
Disk 2 from B to C
Disk 1 from A to C

Java Examples

❮ Java String Concat Java9 Multiresolution Image_Api ❯