Source of Hanoi.java


  1: //Hanoi.java
  2: //Describes the movement of discs to solve the Towers of Hanoi problem.

  4: import java.util.Scanner;

  6: public class Hanoi
  7: {
  8:     public static void main(String[] args)
  9:     {
 10:         System.out.println("\nThis program solves the Tower of Hanoi "
 11:             + "problem by describing the sequence\nof disc moves that "
 12:             + "will achieve the transfer of n discs from the initial"
 13:             + "\npost to the final post, according to the following rules:"
 14:             + "\n\n"
 15:             + "1. Only one disc can be moved at a time.\n"
 16:             + "2. No disc can be placed on top of a smaller disc."
 17:             + "\n\n"
 18:             + "The amount of time to compute the moves increases "
 19:             + "dramatically as the\nnumber of discs increases. For "
 20:             + "illustrative purposes keep the number\nof discs to "
 21:             + "four or five at most.\n");

 23:         Scanner keyboard = new Scanner(System.in);
 24:         int n;
 25:         System.out.print("Enter the number of discs to move: ");
 26:         n = keyboard.nextInt();
 27:         describeDiscMoves(n, 1, 3);
 28:         System.out.println();
 29:     }

 31:     public static void describeDiscMoves(
 32:         int n,
 33:         int startPost,
 34:         int endPost
 35:     )
 36:     /**
 37:     Display the order in which disks must be moved and to which
 38:     posts in order to move n disks from startPost to endPost.
 39:     @param n The number of disks to be moved.
 40:     @param startPost The post holding all disks at the start.
 41:     @param endPost The post to which all disks must be moved.
 42:     <p>Pre:<p>n, startPost and endPost have been initialized.
 43:     <p>Post:<p>All moves necessary for moving n disks from
 44:     startPost to endPost have been displayed.
 45:     */
 46:     {
 47:         int tempPost;
 48:         if (n == 1)
 49:             System.out.println("Move the top disc from post "
 50:                 + startPost + " to post " + endPost + ".");
 51:         else
 52:         {
 53:             tempPost = 6 - startPost - endPost;
 54:             describeDiscMoves(n-1, startPost, tempPost);
 55:             System.out.println("Move the top disc from post "
 56:                 + startPost + " to post " + endPost + ".");
 57:             describeDiscMoves(n-1, tempPost, endPost);
 58:         }
 59:     }
 60: }