Search Tutorials

Tuesday 23 April 2013

Java code to display the solution of Tower of Hanoi using recursion

/*
Program to display the solution of Tower of Hanoi using recursion.
*/
import java.io.*;
class towerOfHanoi
{
public static void main(String args[]) throws IOException
{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
towerOfHanoi call = new towerOfHanoi();
System.out.print("Enter number of discs : ");
int n = Integer.parseInt(br.readLine());
System.out.print("\nLabel of 1st stick : ");
String a = br.readLine();
System.out.print("Label of 2nd stick : ");
String b = br.readLine();
System.out.print("Label of 3rd stick : ");
String c = br.readLine();
call.hanoi(n,a,b,c);
}
void hanoi (int n, String a, String b, String c)
{
if(n==1)
System.out.println("Move disc from " +a +" to " +c);
else
{
hanoi(n-1,a,c,b);
System.out.println("Move disc from " +a +" to " +c);
hanoi(n-1,b,a,c);
}
}
}


/**
* ALGORITHM :
* ---------
* 1. Start
* 2. Accept the number of discs from the user.
* 3. Ask for the labels of sticks A, B & and C.
* 4. Move n−1 discs from A to B. This leaves disc #n alone on stick A.
* 5. Move disc #n from A to C.
* 6. Move n−1 discs from B to C so they sit on disc #n.
* 7. Repeat steps 4 to 6 using recursion.
* 8. End
*/

/*
OUTPUT :
------
Enter number of discs : 4
Label of 1st stick : start
Label of 2nd stick : mid
Label of 3rd stick : end

Move disc from start to mid
Move disc from start to end
....
....
....
....

..
.
.

*/



No comments:

Post a Comment

Back to Top