// Author : Apostolos Syropoulos import java.io.*; public class hanoiE2 { static int moves=0; //number of moves so far static int TowerHeight; //Tower height static int getInt() { String line; BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); try { line = in.readLine(); int i = Integer.valueOf(line).intValue(); return i; } catch (Exception e) { System.err.println("***Error: Input is not a number.\n" + "Input assumed to be the number 1"); return 1; } } static void hanoi(int height, int Pole) { if (height >= 1) { hanoi(height-1, Pole); moveDisk(height, Pole); hanoi(height-1, Neigh(Pole, (TowerHeight - height+1) %2 )); } } static void moveDisk(int disk, int fromPole) { char fromPeg = PoleName(fromPole), toPeg = PoleName(Neigh(fromPole, (TowerHeight - disk) % 2)); moves++; System.out.print(fromPeg); System.out.print(toPeg); System.out.print(((moves % 20)==0) ? '\n' : ' '); } static int Neigh(int Pole, int dir) { return (Pole + dir) % 3 + 1; } static char PoleName(int pole) { switch (pole) { case 1: return 'A'; case 2: return 'B'; case 3: return 'C'; } return 'E'; } public static void main(String[] args) { long time1, time2; //for benchmarking int FromPole=1; System.out.println("Enter Tower height..."); System.out.print("?"); TowerHeight = getInt(); time1 = System.currentTimeMillis(); hanoi(TowerHeight, FromPole); time2 = System.currentTimeMillis(); System.out.println(); System.out.print(time2-time1); //print execution time in msec System.out.println(" msec execution time"); } }