Thursday, October 7, 2010

Towers of Hanoi



/* Towers of Hanoi */

public class TowersOfHanoi
{
private int numDisks; //number of disks to move

public TowersOfHanoi( int disks )
{
numDisks = disks;
}

//recursively more disks between towers
public void solveTowers(int disks, int sourcePeg, int destinationPeg, int tempPeg)
{

//base case -- only one disk to move

if( disks == 1)
{
System.out.printf("\n%d --> %d",sourcePeg, destinationPeg);
return;
}

//recursion step -- move (disk -1) disk from sourcePeg
//to tempPEg using destinationPeg

solveTowers(disks-1,sourcePeg,tempPeg,destinationPeg);

//move last disk from sourcePeg to destinationPeg

System.out.printf("\n%d --> %d", sourcePeg, destinationPeg);

//move (disk-1) disk from tempPeg to destinationPeg

solveTowers( disks - 1, tempPeg, destinationPeg, sourcePeg);
}
}

--------------------------------------------------------------------


/* Main function to be run */

public class TowersOfHanoiTest

{
public static void main( String args[])
{

int startPeg = 1; // value 1 used to indicate startPeg in output
int endPeg = 3; // value 3 usedto indicate endPeg in output
int tempPeg = 2; // value 2 used to indicate tempPeg output
int totalDisks = 3; // number of disks

TowersOfHanoi towersOfHanoi = new TowersOfHanoi(totalDisks);

//initial nonrecursive call: move all disks

towersOfHanoi.solveTowers(totalDisks, startPeg, endPeg, tempPeg);
}
}

No comments:

Post a Comment