Latest web development tutorials

Java Examples - Tower of Hanoi algorithm

Java Examples Java Examples

Tower of Hanoi (also known as the Tower of Hanoi) problem stems from an ancient Indian legend of educational toys. A time when Brahma created the world to do three diamond pillars, a pole from the bottom up in order of size pile with 64 gold discs. Great Brahma Brahman command to the disk from the bottom in order of size repositioned on the other pillars. And provides disk can not zoom in on a small disc, you can only move one disc between the three pillars.

Later, this evolved into the legendary Tower of Hanoi game, play as follows:

  • 1. There are three poles A, B, C. A rod has a number of dishes
  • 2. Each move a plate, only a small stack in a big top
  • 3. All dishes from A to move the lever all the C pole

The following example demonstrates HANOR algorithm:

/*
 author by w3cschool.cc
 MainClass.java
 */
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 is run output 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 Examples Java Examples