forked from AndrewProgramming/JavaTutorialCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTowersOfHanoi.java
More file actions
37 lines (32 loc) · 981 Bytes
/
TowersOfHanoi.java
File metadata and controls
37 lines (32 loc) · 981 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package recursive;
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);
}
}
}