public class Hanoi { /* This program displays the sequence of moves required to solve the Towers of Hanoi problem. The problem requires n disks of different diameters placed on one of three pegs, with the largest disk on the bottom of the pile. In a sequence of single-disk moves, the entire pile should be transferred to the third peg, with the additional proviso that at no time is a larger disk placed on top of a smaller disk. The third peg is used at each stage as an auxiliary peg. The solution is done as a recursive method Move, which breaks the n-disk problem into two n-1 disk problems and a single disk move in between. This is the essence of the "Divide and Conquer" strategy of problem solving. */ static void Move( int nDisks, char StartPeg, char AuxPeg, char EndPeg) { /* This method recursively solves the problem for any number of disks nDisks, and any particular starting, ending, and auxiliary peg Note that the roles of the pegs are changing with each recursive call. */ if (nDisks == 1) // base case -- stopping point for recursion System.out.println( " Move disk from " + StartPeg + " to " + EndPeg); else { // recursive calls to Move with n - 1 disks // Move n - 1 disks from StartPeg to AuxPeg using EndPeg Move( nDisks - 1, StartPeg, EndPeg, AuxPeg ); // Move 1 disk from StartPeg to EndPeg - no auxiliary peg needed Move( 1, StartPeg, ' ', EndPeg ); // Move n - 1 disks from AuxPeg to EndPeg using StartPeg Move( nDisks - 1, AuxPeg, StartPeg, EndPeg ); } } public static void main (String argv[]) { final char Peg1 = 'A', // Identities of the three pegs Peg2 = 'B', Peg3 = 'C'; int NumDisks; // number of disks for the problem System.out.print( "Enter number of disks: " ); NumDisks = Keyboard.readInt(); while(!Keyboard.eof()) { Move( NumDisks, Peg1, Peg2, Peg3 ); System.out.print( "\nEnter number of disks: " ); NumDisks = Keyboard.readInt(); } } }