package com.algorithmes;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* The Towers of Hanoi problem using Recursion in Java
* Author: Guru
*/
public class TowersOfHanoi {
/**
* @param args
*/
static int moves =1;
public static void main(String[] args) {
int n=0;
System.out.println("Enter the value for N:");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
//Read the value
n=Integer.parseInt(br.readLine());
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// The towers is a function to solve the Towers of Henoi
towers(n,'A','B','C');
}
/**
* The recursive method for the towers problem
* @param n
* @param c
* @param d
* @param e
*/
private static void towers(int n, char from, char to, char via) {
if(n==1)
System.out.println("Move "+moves+++" from "+from+" to "+to);
else{
towers(n-1,from,via,to);
System.out.println("Move "+moves+++" from "+from+" to "+to);
towers(n-1,via,to,from);
}
}
}
The output of the Towers of Hanoi using Recursion in Java is:
Enter the value for N:
3
Move 1 from A to B
Move 2 from A to C
Move 3 from B to C
Move 4 from A to B
Move 5 from C to A
Move 6 from C to B
Move 7 from A to B