// This file defines a class that demonstrates a recursive solution to the Towers // of Hanoi puzzle. I encapsulate the solution in a "solvable towers of Hanoi" class, // that extends the standard Towers of Hanoi class by providing a "solve" method (and, // for convenience, a main program method). // History // Feb. 2002 -- Created by Doug Baldwin import tower.*; class SolvableTower extends TowersOfHanoi { // The constructor. This creates a solvable tower puzzle of the specified size // by simply asking the superclass to make a puzzle of that size. public SolvableTower( int size ) { super( size ); } // solve. This method solves a Towers of Hanoi puzzle by moving n disks from pole // source to pole destination, using pole spare to get other disks out of the way. // This uses the standard algorithm, namely if there are no disks to move you're done, // otherwise move the top n-1 disks to the spare pole to get them out of the way, move // the bottom disk to destination, and then move the disks on the spare pole to the // destination. public void solve( int n, int source, int destination, int spare ) { if ( n > 0 ) { this.solve( n-1, source, spare, destination ); this.diskMove( source, destination ); this.solve( n-1, spare, destination, source ); } } // The main program. This creates a solvable puzzle and then asks it to solve // itself. public static void main( String args[] ) { final int size = 6; // The number of disks in this puzzle SolvableTower puzzle = new SolvableTower( size ); puzzle.setDelayTime( 500 ); puzzle.solve( size, 1, 3, 2 ); } }