Java Hanoi puzzle

Solve Hanoi puzzle

The Tower of Hanoi is a mathematical puzzle. It consists of three rods, and a number of disks of different sizes which can slide onto any rod. The puzzle starts with the disks in a neat stack in ascending order of size on one rod, the smallest at the top, thus making a conical shape.

Referened from http://en.wikipedia.org/wiki/Tower_of_Hanoi

public class Main {
  static int nDisks = 3;
/*from w w w .j  a v a2s .  c  om*/
  public static void main(String[] args) {
      hanoiTower(nDisks, 'A', 'B', 'C');
  }

  public static void hanoiTower(int topN, char src, char inter, char dest) {
    if (topN == 1)
        System.out.println("Disk 1 from " + src + " to " + dest);
    else {
        // src to inter
        hanoiTower(topN - 1, src, dest, inter);
        // move bottom
        System.out.println("Disk " + topN + " from " + src + " to " + dest);
        //inter to dest
        hanoiTower(topN - 1, inter, src, dest);
    }
  }
}

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. Convert Fahrenheit to Celsius
Home »
  Java Tutorial »
    Java Langauge »
      Java Algorithms
Java Bubble sort
Java Binary Search
Java Insertion Sort
Java Selection sort
Java Shell sort
Java Heap Sort
Java Merge Sort
Java Quick Sort
Java Fibonacci
Java Hanoi puzzle
Java Fahrenheit to Celsius