public class Hanoi extends basic { /* 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 expressed as a recursive method Move, which breaks the n-disk problem into two n-1 disk problems and a single disk move. This is the essence of the "Divide and Conquer" strategy of problem solving. */ public static void main (String argv[]) throws Exception { char Peg1 = 'A', // Identities of the three pegs Peg2 = 'B', Peg3 = 'C'; int NumDisks; // number of disks for the problem input in = new input(); output out = new output(); out.write( "Enter number of disks, or 0 to quit: " ); NumDisks = in.readint(); while(NumDisks != 0) { Move( NumDisks, Peg1, Peg2, Peg3, out ); out.write( "\nEnter number of disks, or 0 to quit: " ); NumDisks = in.readint(); } } static void Move (int nDisks, char StartPeg, char AuxPeg, char EndPeg, output out) throws Exception /* 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 solve the 1-disk problem out.writeln( "Move disk from " + StartPeg + " to " + EndPeg); else { // recursive case to solve the n-disk problem (n>1) // Move n-1 disks from StartPeg to AuxPeg using EndPeg Move( nDisks-1, StartPeg, EndPeg, AuxPeg, out ); // Move 1 disk from StartPeg to EndPeg - no auxiliary needed Move( 1, StartPeg, ' ', EndPeg, out ); // Move n-1 disks from AuxPeg to EndPeg using StartPeg Move( nDisks - 1, AuxPeg, StartPeg, EndPeg, out ); } } }