/* ======================================================== The classic Tower of Hanoi function, but rewritten as a "devide and conquer" algorithm ======================================================== */ import java.util.Scanner; public class Hanoi { static String hanoi(int nDisks, int fromPeg, int toPeg) { String helpSol1, helpSol2; // String contains the moves String MyStep, mySol; if ( nDisks == 1 ) { return fromPeg + " -> " + toPeg + "\n"; // solution move } else { int helpPeg = 6 - fromPeg - toPeg; // Ask 2 helpers to solve 2 smaller problems helpSol1 = hanoi(nDisks-1, fromPeg, helpPeg); helpSol2 = hanoi(nDisks-1, helpPeg, toPeg); // Use solutions of smaller problems to solve my problem: MyStep = fromPeg + " -> " + toPeg + "\n"; mySol = helpSol1 + MyStep + helpSol2; // + = concatenate // Return my solution return mySol; } } public static void main(String[] args) { Scanner in = new Scanner( System.in ); System.out.print("NDisks = "); int N = in.nextInt(); System.out.print("From peg = "); int from = in.nextInt(); System.out.print("To peg = "); int to = in.nextInt(); String sol = hanoi( N, from, to); System.out.println("\n\nSolution:"); System.out.println("======================="); System.out.println(sol); } }