Search This Blog

Java Program to Solve Tower of Hanoi Puzzle Problem

This is a java program to solve towers of hanoi puzzle problem. This simple java program gives solution for tower of hanoi problem with any number of disks. Tower of Hanoi is a mathematical game or puzzle. It is also called tower of brahma or Lucas' tower. There are three towers (or rods) and a number of disks of different diameters. Initially, The disks have hole at center so that it can slide on to the rods. Initially all disks are stacked on the first tower, say tower A, such that no disk is placed over a smaller disk. The goal or objective is to move all these disks from tower A (first tower) to tower C (third tower). But you should obey the following rules. The rules of towers of hanoi puzzle are:

  1. Only one disk can be taken at a time.
  2. It is not allowed to take any disk other the topmost one from a tower.
  3. Never place a larger disk on top of a smaller one.
  4. Place a disk nowhere else other than on tower.

The java program here displays the optimal solution for towers of Hanoi problem. You can enter the number of disks when you start. The program lists an optimal number of moves to solve the tower of Hanoi puzzle. The solution is always optimal. For a 3 disks puzzle, the optiomal number of moves is 7. This c program uses a recursive function to find the solution of tower of Hanoi puzzle. The program is as follows.


import java.util.Scanner;

public class Hanoi{

static void moveTopN(int n, int a, int b, int c)
//to Move top n disk from tower a to tower c
//Uses tower b for swapping
{
if(n>=1)
    {
    moveTopN(n-1,a,c,b);
    System.out.printf("\nMove top disk from tower %d to tower %d",a,c);
    moveTopN(n-1,b,a,c);
    }
}

public static void main(String[] args)
{
int n;
System.out.printf("Enter number of disks");
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
moveTopN(n,1,2,3);
}
}

No comments:

Post a Comment