Hanoi.java


Below is the syntax highlighted version of Hanoi.java from §2.7 Recursion.

/*************************************************************************
 *  Compilation:  javac Hanoi.java
 *  Execution:    java Hanoi N
 *  
 *  Solves the Towers of Hanoi problem on N discs. The discs are labeled
 *  in increasing order of size from 1 to N and the poles are labeled
 *  A, B, and C.
 *
 *  % java Hanoi 3
 *  Move disc 1 from A to C
 *  Move disc 2 from A to B
 *  Move disc 1 from C to B
 *  Move disc 3 from A to C
 *  Move disc 1 from B to A
 *  Move disc 2 from B to C
 *  Move disc 1 from A to C
 *
 *************************************************************************/

public class Hanoi {

    // move n smallest discs from one pole to another, using the temp pole
    public static void hanoi(int n, String from, String temp, String to) {
        if (n == 0) return;
        hanoi(n-1, from, to, temp);
        System.out.println("Move disc " + n + " from " + from + " to " + to);
        hanoi(n-1, temp, from, to);
    }

    public static void main(String[] args) {
        int N = Integer.parseInt(args[0]);
        hanoi(N, "A", "B", "C");
    }
}




Last updated: Mon Oct 4 13:16:43 EDT 2004 .
Copyright © 2004, Robert Sedgewick and Kevin Wayne.