Towers of Hanoi in Java

Towers of Hanoi or Tower of Brahma or Lucas’ Tower

Tower of Hanoi is a mathematical game or puzzle. It consists of three rods(towers), and a number of disks of different sizes which can slide onto any rod. The puzzle starts with the disks in a neat stack in ascending order of size on one rod, the smallest at the top, thus making a conical shape.

The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules:

  • Only one disk can be moved at a time.
  • Each move consists of taking the upper disk from one of the towers and placing it on top of another tower i.e. a disk can only be moved if it is the uppermost disk on a tower.
  • No disk may be placed on top of a smaller disk.

 

 

Solving Towers of Hanoi

Here is the Java program for Towers of Hanoi using recursion.

package com.topjavatutorial.app;

public class TowersOfHanoi {

  public static void main(String[] args) {
    char startPeg = 'A'; // start tower in output
    char endPeg = 'C'; // end tower in output
    char tempPeg = 'B'; // temporary tower in output
    int totalDisks = 3; // number of disks

    solveTowers(totalDisks, startPeg, endPeg, tempPeg);
  }

  private static void solveTowers(int n, char startPeg, char endPeg,
      char tempPeg) {
    if (n > 0) {
      solveTowers(n - 1, startPeg, tempPeg, endPeg);
      System.out.printf("Move disk from %c to %c\n", startPeg, endPeg);
      solveTowers(n - 1, tempPeg, endPeg, startPeg);
    }

  }

}

Output :

Move disk from A to C
Move disk from A to B
Move disk from C to B
Move disk from A to C
Move disk from B to A
Move disk from B to C
Move disk from A to C

 

© 2017, https:. All rights reserved. On republishing this post, you must provide link to original post

Leave a Reply.. code can be added in <code> </code> tags