Welcome Message

Hi, welcome to my website. This is a place where you can get all the questions, puzzles, algorithms asked in interviews and their solutions. Feel free to contact me if you have any queries / suggestions and please leave your valuable comments.. Thanks for visiting -Pragya.

January 4, 2010

My Hanoi Prog

public class TowerOfHanoi {

static int moves = 0;
public static void main(String[] args) {
char fromPole = 'A';
char toPole = 'B';
char withPole = 'C';
hanoi(3, fromPole, toPole, withPole);
}
public static void hanoi(int height , char fromPole , char toPole , char withPole){
if(height >= 1){
hanoi(height - 1, fromPole, withPole ,toPole);
move(fromPole , toPole);
hanoi(height - 1,withPole,toPole , fromPole );
}
}
public static void move(char fromPole , char toPole){
moves++;
System.out.println("****Next Move****");
System.out.print(fromPole+ "-->");
System.out.println(toPole);
}
}


Output is :
****Next Move****
A-->B
****Next Move****
A-->C
****Next Move****
B-->C
****Next Move****
A-->B
****Next Move****
C-->A
****Next Move****
C-->B
****Next Move****
A-->B

No comments: