Tower Of Hanoi | Code Tutorial

The Tower of Hanoi (also called the Tower of Brahma or Lucas' Tower and sometimes pluralized) is a mathematical game or 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.

public class Main {

	public static void tower(int n, char sourceRod, char destinationRod,
			char auxiliaryRod) {
		if (n == 0) {
			return;
		}
		int x = n - 1;
		System.out.println("tower("+x+", "+sourceRod+", "+auxiliaryRod+", "+destinationRod+")");
		tower(n - 1, sourceRod, auxiliaryRod, destinationRod);
		System.out.println("Move the disk " + n + " from " + sourceRod
				+ " to " + destinationRod);
		System.out.println("tower("+x+", "+auxiliaryRod+", "+destinationRod+", "+sourceRod+")");
		tower(n - 1, auxiliaryRod, destinationRod, sourceRod);		
	}

	public static void main(String[] args) {
		System.out.println("tower(3, 'S', 'D', 'A')");
		tower(3, 'S', 'D', 'A');
	}

}