Java Examples - Tower of Hanoi Algorithm

Java 实例Java Examples

The Tower of Hanoi (also known as the Hanoi Tower) problem is an educational toy originating from an ancient Indian legend. When Brahma created the world, he made three diamond pillars and stacked 64 golden discs on one pillar from bottom to top in order of size. Brahma commanded the Brahmins to reposition the discs onto another pillar starting from the bottom in order of size. It was also stipulated that a larger disc cannot be placed on a smaller disc, and only one disc could be moved at a time between the three pillars.

Later, this legend evolved into the Tower of Hanoi game. The rules are as follows:

  • 1. There are three rods A, B, C. There are several discs on rod A.
  • 2. Only one disc is moved at a time, and a smaller disc can only be placed on top of a larger one.
  • 3. Move all discs from rod A to rod C.

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 output of running the above code is:

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 实例Java Examples

Other Extensions