public class TowersOfHanoi
1: // Fig. 15.15: TowersOfHanoi.java
2: // Program solves the towers of Hanoi problem, and
3: // demonstrates recursion.
4:
5: public class TowersOfHanoi
6: {
7: private int numDisks; // number of disks to move
8:
9: public TowersOfHanoi( int disks )
10: {
11: numDisks = disks;
12: } // end constructor TowersOfHanoi
13:
14: // recusively move disks through towers
15: public void solveTowers( int disks, int sourcePeg, int destinationPeg,
16: int tempPeg )
17: {
18: // base case -- only one disk to move
19: if ( disks == 1 )
20: {
21: System.out.printf( "\n%d --> %d", sourcePeg, destinationPeg );
22: return;
23: } // end if
24:
25: // recursion step -- move disk to tempPeg, then to destinationPeg
26: // move ( disks - 1 ) disks from sourcePeg to tempPeg recursively
27: solveTowers( disks - 1, sourcePeg, tempPeg, destinationPeg );
28:
29: // move last disk from sourcePeg to destinationPeg
30: System.out.printf( "\n%d --> %d", sourcePeg, destinationPeg );
31:
32: // move ( disks - 1 ) disks from tempPeg to destinationPeg
33: solveTowers( disks - 1, tempPeg, destinationPeg, sourcePeg );
34: } // end method solveTowers
35: } // end class TowersOfHanoi
36:
37: /*************************************************************************
38: * (C) Copyright 1992-2005 by Deitel & Associates, Inc. and *
39: * Pearson Education, Inc. All Rights Reserved. *
40: * *
41: * DISCLAIMER: The authors and publisher of this book have used their *
42: * best efforts in preparing the book. These efforts include the *
43: * development, research, and testing of the theories and programs *
44: * to determine their effectiveness. The authors and publisher make *
45: * no warranty of any kind, expressed or implied, with regard to these *
46: * programs or to the documentation contained in these books. The authors *
47: * and publisher shall not be liable in any event for incidental or *
48: * consequential damages in connection with, or arising out of, the *
49: * furnishing, performance, or use of these programs. *
50: *************************************************************************/