Assignment 360 - Towers of Hanoi / Test and Image result
/*
Towers of Hanoi
*/
public class TowersOfHanoi
{
private int numDisks; //number od idsks to move
public TowersOfHanoi( int disks )
{
numDisks = disks;
}
//recursively more diks 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;
}
//recursing step -- move (disk - 1) disks 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 (disks - 1) disks from tempPeg to destinationPeg
solveTowers( disks - 1, tempPeg, destinationPeg, sourcePeg);
}
}
TowersOfHanoiTest
/*
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 used to 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