Friday, October 25, 2013

TOWER OF HANOI IN JAVA.

/*

TOPIC: TOWER OF HANOI.
DATE:2/8/2012

*/
import java.io.*;
class toh
{
public static void main(String args[]) throws IOException
{
hanoi obj=new hanoi();
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
System.out.println("enter no. of rings");
int n=Integer.parseInt(br.readLine());
obj.ha('A','B','C',n);
}
}

class hanoi
{
void ha(char a,char b,char c,int n)
{
if(n==0)
System.out.println("wrong input bummer!");
if(n==1)
System.out.println("move from"+a+" to "+c);
if(n>1)
   {
ha(a,c,b,n-1);
ha(a,b,c,1);
ha(b,a,c,n-1);
   }
}
}
/*
OUTPUT:
bash-3.00$ PATH="/usr/local/jdk1.6.0_11/bin"
bash-3.00$ javac hanoi.java
bash-3.00$ java toh
enter no. of rings
3
move fromA to C
move fromA to B
move fromC to B
move fromA to C
move fromB to A
move fromB to C
move fromA to C

*/

No comments:

Post a Comment