TOWER OF HANOI

/* Towers of Hanoi Program
The Towers of Hanoi problem is a complex example of a recursive algorithm,
yet the function itself is quite simple. The goal is to move a set of disks
from one peg to another. The disks are on one of three pegs with the
smallest disk on the top, and the largest on the bottom. You must move all
the disks from one peg to another, but you can only move one disk at a time,
you can only store disks on pegs, and you can not put a larger disk on top
of a smaller disk.
*/
import java.io.*;
class HANOI
{
int ctr=0;
void SolveTower( int Disks, char FromPeg, char ToPeg, char AuxPeg )
{
ctr++;
if( Disks==1 )
System.out.println(“Move from “+FromPeg+” to “+ToPeg);
else
{
SolveTower( Disks-1, FromPeg, AuxPeg, ToPeg );
System.out.println(“Move from “+FromPeg+” to “+ToPeg);
SolveTower( Disks-1, AuxPeg, ToPeg, FromPeg );
}
}
void main() throws IOException
{
InputStreamReader ISR=new InputStreamReader(System.in);
BufferedReader x= new BufferedReader(ISR);
int Disks;
System.out.print(“How many disks? “);
Disks=Integer.parseInt(x.readLine());
SolveTower( Disks, ‘1’, ‘3’, ‘2’ );
System.out.print(“Solved in “+ctr+” moves”);
}
}

Leave a Comment