-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathHanoiTowers.java
69 lines (57 loc) · 1.89 KB
/
HanoiTowers.java
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package by.andd3dfx.recursion;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import java.util.ArrayDeque;
import java.util.Deque;
/**
* @see <a href="https://youtu.be/8fkHg9JKKmg">Video solution</a>
*/
@Getter
public class HanoiTowers {
@RequiredArgsConstructor
public class Column {
private final String name;
@Getter
private Deque<Integer> stack = new ArrayDeque<>();
}
private final int height;
private Column left;
private Column middle;
private Column right;
public HanoiTowers(int height) {
this.height = height;
left = new Column("Left");
for (int i = 0; i < height; i++) {
left.stack.push(height - i);
}
middle = new Column("Middle");
right = new Column("Right");
}
public void solve() {
moveUpperNDisksFromColumnIToColumnJUsingColumnKIfNeeded(height, left, right, middle);
}
private void moveUpperNDisksFromColumnIToColumnJUsingColumnKIfNeeded(int n, Column from, Column to, Column tmp) {
if (n > 1) {
moveUpperNDisksFromColumnIToColumnJUsingColumnKIfNeeded(n - 1, from, tmp, to);
}
moveDisk(from, to);
if (n > 1) {
moveUpperNDisksFromColumnIToColumnJUsingColumnKIfNeeded(n - 1, tmp, to, from);
}
}
private void moveDisk(Column from, Column to) {
Integer disk = from.stack.pop();
System.out.println("Moved disk " + disk + " from " + from.name + " to " + to.name);
validate(disk, to);
to.stack.push(disk);
}
private void validate(Integer disk, Column to) {
if (to.stack.isEmpty()) {
return;
}
if (disk < to.stack.peek()) {
return;
}
throw new IllegalStateException("Placement of this disk is forbidden!");
}
}