I am just getting into recursion and I think I have a basic understanding of how it works. I have this code for a Tower of Hanoi problem and I have been staring at it for an hour trying to figure out exactly what it is doing. The method 'moveDisks' is confusing to me. I was hoping someone could help explain what's going on in the method. I didn't write it.
To try to understand I ran the code and put 2 for the number of disks. Here is what printed out:
The moves are: Move disk 1 from A to C, Move disk 2 from A to B, Move disk 1 from C to B
So, if I understand it right, the 2 brings us to the 'else' block which means that 2-1 is going to move from A to C. And then it subtracts 1 again to do another move? I don't understand what happens next or why the need to alternate towers.
import java.util.Scanner;
public class TowersOfHanoi {
/** Main method */
public static void main(String[] args) {
// Create a Scanner
Scanner input = new Scanner(System.in);
System.out.print("Enter number of disks: ");
int n = input.nextInt();
// Find the solution recursively
System.out.println("The moves are:");
moveDisks(n, 'A', 'B', 'C');
}
/** The method for finding the solution to move n disks
from fromTower to toTower with auxTower */
public static void moveDisks(int n, char fromTower,
char toTower, char auxTower) {
if (n == 1) // Stopping condition
System.out.println("Move disk " + n + " from " +
fromTower + " to " + toTower);
else {
moveDisks(n - 1, fromTower, auxTower, toTower);
System.out.println("Move disk " + n + " from " +
fromTower + " to " + toTower);
moveDisks(n - 1, auxTower, toTower, fromTower);
}
}
}