COP 3337 Section U05 Spring 2016 THE TOWERS OF HANOI =================== The program: public class Hanoi { // test the towers of Hanoi public static void main(String[] args) { System.out.println("The Towers of Hanoi"); System.out.println("===================\n\n\n"); // test the problem for n=3 System.out.println("We test the problem for n = 3."); System.out.println("We move the 3 disks from A to C, using B.\n"); hanoi(3,'A','C','B'); // test the problem for n=4 System.out.println("\nWe test the problem for n = 4."); System.out.println("We move the 4 disks from A to C, using B.\n"); hanoi(4,'A','C','B'); } // this program solves the towers of hanoi problem private static void hanoi(int n, char from, char to, char aux) { if (n <= 0 ) { // print error message System.out.println("The number must be positive!"); return; } if (n == 1) { System.out.println("Move disk 1 from " + from + " to " + to + "."); } else // recurse { // move n-1 disks from to to aux hanoi(n-1,from,aux,to); // move the big disk to to System.out.println("Move disk " + n + " from " + from + " to " + to + "."); // move the n-1 disks from aux to to hanoi(n-1, aux, to, from); } } } The output: run: The Towers of Hanoi =================== We test the problem for n = 3. We move the 3 disks from A to C, using B. Move disk 1 from A to C. Move disk 2 from A to B. Move disk 1 from C to B. Move disk 3 from A to C. Move disk 1 from B to A. Move disk 2 from B to C. Move disk 1 from A to C. We test the problem for n = 4. We move the 4 disks from A to C, using B. Move disk 1 from A to B. Move disk 2 from A to C. Move disk 1 from B to C. Move disk 3 from A to B. Move disk 1 from C to A. Move disk 2 from C to B. Move disk 1 from A to B. Move disk 4 from A to C. Move disk 1 from B to C. Move disk 2 from B to A. Move disk 1 from C to A. Move disk 3 from B to C. Move disk 1 from A to B. Move disk 2 from A to C. Move disk 1 from B to C. BUILD SUCCESSFUL (total time: 6 seconds)