Showing posts with label Towers Of Hanoi. Show all posts
Showing posts with label Towers Of Hanoi. Show all posts

Thursday, July 7, 2011

Program to find solution for Towers Of Hanoi

import java.io.DataInputStream;   // to load DataInputStream class 
       
class TowerOfHanoi
{
public static void main(String args[ ])
{
            int n=0;
           DataInputStream in = new DataInputStream(System.in); 
                       try
{
                                System.out.print(“Enter number of rings : “);
                                n = Integer.parseInt(in.readLine());
}
           catch(Exception e) {  System.out.println(“I/O Error”);   }
                      Hanoi(n);
}
static void MoveDisc (int whichdisc , char frompeg , char topeg )
{
System.out.println(“Move ring “+whichdisc+” from peg “+frompeg+” to peg “+topeg);
}
static void MoveTower (int height, char frompeg, char topeg, char usingpeg)
{
if (height <= 0) {    // nothing to move!     }
else
{
MoveTower (height-1, frompeg, usingpeg, topeg);
MoveDisc (height, frompeg, topeg);
MoveTower (height-1, usingpeg, topeg, frompeg);
}
}
static void Hanoi(int n) 
{
MoveTower(n,'A','B','C');
}
}


/*
Execution :
C:\javac TowerOfHanoi.java
C:\java TowerOfHanoi


Output :
Enter number of rings : 3
Move ring 1 from peg A to peg B
Move ring 2 from peg A to peg C
Move ring 1 from peg B to peg C
Move ring 3 from peg A to peg B
Move ring 1 from peg C to peg A
Move ring 2 from peg C to peg B
Move ring 1 from peg A to peg B


*/