Towers of Hanoi

Towers of Hanoi

The minimum number of moves required to solve a Tower of Hanoi puzzle is 2^n – 1, where n is the number of disks.

Recursion

import java.util.Scanner;

public class TowersOfHanoi {
	private static int move = 1;

	public static void main(String args[]) {
		System.out.println("Enter number of Disks:");
		Scanner sc = new Scanner(System.in);
		int x = sc.nextInt();
		solve(x, 'A', 'B', 'C');
	}

	public static void solve(int n, char srcPeg, char destPeg, char auxPeg) {
		if (n == 1) {
			System.out.println(move + ": Moved Disk from " + srcPeg + " to "
					+ destPeg);
			move++;
			return;
		}
		solve(n - 1, srcPeg, auxPeg, destPeg);

		System.out.println(move + ": Moved Disk from " + srcPeg + " to "
				+ destPeg);
		move++;
		solve(n - 1, auxPeg, destPeg, srcPeg);
	}
}


Leave a Reply

Your email address will not be published. Required fields are marked *