public class TowersOfHanoi {
/**
* This method solve the towers of hanoi problem.
* @param numberOfDisks number of disks to move.
* @param source source tower.
* @param destination destination tower.
* @param auxiliar auxiliar tower.
*/
public void solveTowers(int numberOfDisks, int source, int destination, int auxiliar) {
//If there is only one disk to move
if (numberOfDisks == 1) {
//Move the disk from source to destination
moveDisk(source, destination);
} else {
//Move the first n-1 disks from source to auxiliar tower
solveTowers(numberOfDisks - 1, source, auxiliar, destination);
//Move the last disk from source to destination
moveDisk(source, destination);
//Move the n-1 disks from auxiliar to destination tower
solveTowers(numberOfDisks - 1, auxiliar, destination, source);
}
}
/**
* This method move a disk from source to destination.
* @param source source tower.
* @param destination destination tower.
*/
public void moveDisk(int source, int destination) {
System.out.println("Move disk from " + source + " to " + destination);
}
/**
* One Example
*/
public static void main(String args[]) throws IOException {
TowersOfHanoi towersOfHanoi= new TowersOfHanoi ();
//Example
towersOfHanoi.solveTowers(3, 1, 3, 2);
}
}
For further actions, you may consider blocking this person and/or reporting abuse
Top comments (0)