AnimatedHanoi.java


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

/*************************************************************************
 *  Compilation:  javac AnimatedHanoi.java
 *  Execution:    java AnimatedHanoi N
 *  Dependencies: StdDraw.java
 *  
 *  Solves the Towers of Hanoi problem on N discs and displays the
 *  results graphically.
 *
 *
 *  % java AnimatedHanoi 6
 *
 *************************************************************************/

import java.awt.Color;

public class AnimatedHanoi {
   static int N;               // number of discs
   static int height = 20;     // height of each disc
   static int width  = 200;    // width of largest discs
   static char[] whichPole;    // whichPole[i] = pole that disc i is on:  A, B, or C


   // draw the current state of the Towers of Hanoi game
   public static void draw() {

      // clear the screen
      StdDraw.clear();

      // draw 3 poles
      StdDraw.setColor(Color.black);
      for (int i = 1; i <= 3; i++) {
         StdDraw.go(i * width, height * N / 2.0);
         StdDraw.spot(2, height * N);
      }

      // draw N discs
      int[] discs = new int[3 + 1];
      for (int i = N; i >= 1; i--) {
         double size = 0.5 * width * i / N;
         int pole = whichPole[i] - 'A' + 1;    // convert from A, B, C to 1, 2, 3
         StdDraw.go(pole * width, height * (discs[pole] + 0.5));

         // color discs according to rainbow
         StdDraw.setColorHSB(1.0 * i / N, 1.0, 1.0);
         StdDraw.spot(size, height);

         ++discs[pole];
      }

      StdDraw.pause(500);
   }

   public static void hanoi() { draw(); hanoi(N, 'A', 'B', 'C'); }

   public static void hanoi(int n, char from, char temp, char to) {
      if (n == 0) return;
      hanoi(n-1, from, to, temp);
      System.out.println("Move disc " + n + " from " + from + " to " + to);
      whichPole[n] = to;
      draw();
      hanoi(n-1, temp, from, to);
   }

   public static void main(String[] args) {
      N = Integer.parseInt(args[0]);
      whichPole = new char[N + 1];
      for (int i = 1; i <= N; i++)
         whichPole[i] = 'A';
      StdDraw.create(4 * width,  height * (N + 3) );
      hanoi();
   }
}


Last updated: Sun Sep 26 12:31:34 EDT 2004 .
Copyright © 2004, Robert Sedgewick and Kevin Wayne.