-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTowersOfHanoi.java
More file actions
47 lines (28 loc) · 905 Bytes
/
Copy pathTowersOfHanoi.java
File metadata and controls
47 lines (28 loc) · 905 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
38
39
40
41
42
43
44
45
46
47
public class TowersOfHanoi {
private int totalDisks;
private int step;
TowersOfHanoi() {
totalDisks = 0;
}
TowersOfHanoi(int disks) {
totalDisks = disks;
step = 1;
}
public void solve() {
moveTower(totalDisks, 1, 3, 2);
}
private void moveTower(int totalDisks, int start, int end, int temp) {
if (totalDisks == 1) {
moveOneDisk(start, end);
} else {
moveTower(totalDisks - 1, start, temp, end);
moveOneDisk(start, end);
moveTower(totalDisks - 1, temp, end, start);
}
}
private void moveOneDisk(int start, int end) {
System.out.println("Step #" + step + "-----");
System.out.println("Action: Move one disk from tower #" + start + " to tower #" + end);
step++;
}
}