data-structures/java/Stack/TOH.java

33 lines
1.1 KiB
Java
Raw Normal View History

2022-09-13 13:55:58 +00:00
/** Towers of Hanoi */
public enum operation { MOVE, TOH }
class TOHobj {
public operation op;
public int num;
public Pole start, goal, temp;
/** Recursive call operation */
TOHobj(operation o, int n, Pole s, Pole g, Pole t)
{ op = o; num = n; start = s; goal = g; temp = t; }
/** MOVE operation */
TOHobj(operation o, Pole s, Pole g)
{ op = o; start = s; goal = g; }
}
static void TOH(int n, Pole start, Pole goal, Pole temp) {
// Make a stack just big enough
Stack<TOHobj> S = new AStack<TOHobj>(2 * n + 1);
S.push(new TOHobj(operation.TOH, n, start, goal, temp));
while (S.length() > 0) {
TOHobj it = S.pop(); // Get next task
if (it.op == operation.MOVE) // Do a move
move(it.start, it.goal);
else if (it.num > 0) { // Imitate TOH recursive solution (in reverse)
S.push(new TOHobj(operation.TOH, it.numm - 1, it.temp, it.goal, it.start));
S.push(new TOHobj(operation.MOVE, it.start, it.goal)); // A move to do
S.push(new TOHobj(operation.TOH, it.num - 1, it.start, it.temp, it.goal));
}
}
}