import java.util.Scanner;
/**
* Recursion!
* The towers of Hanoi
* @author gtowell
* Created Oct 2019
* Modified: Oct 24, 2020
*/
public class TowersOfHanoi
{
/** The number of moves made */
private int moveCount = 0;
/**
* Doing all the recursive work. This fucntion will print out the
* sequence of moved needed to solve a tower of hanoi problem of a given height
* @param n the height of the tower
* @param start The tower that the disks are on
* @param auxiliary The spare tower
* @param end The Tower that you want disks to move to
*/
public void solve(int n, String start, String auxiliary, String end)
{
if (n == 1) { // base case of the recursion
moveCount++;
System.out.println(moveCount + " " + start + " -> " + end);
return;
}
else { // doing the work.
solve(n - 1, start, end, auxiliary);
moveCount++;
System.out.println(moveCount + " " + start + " -> " + end);
solve(n - 1, auxiliary, start, end);
}
return;
}
/**
* Run the code, getting the number of disks in the twoer from the user.
* @param args
*/
public static void main(String[] args)
{
TowersOfHanoi towersOfHanoi = new TowersOfHanoi();
System.out.print("Enter number of discs: ");
try (Scanner scann = new Scanner(System.in);) {
towersOfHanoi.solve(scann.nextInt(), "A", "B", "C");
}
}
}