mirror of
https://git.adityakumar.xyz/data-structures.git
synced 2024-12-22 19:52:52 +00:00
towers of hanoi
This commit is contained in:
parent
0fda2fa4cc
commit
415068bc21
1 changed files with 32 additions and 0 deletions
32
java/Stack/TOH.java
Normal file
32
java/Stack/TOH.java
Normal file
|
@ -0,0 +1,32 @@
|
||||||
|
/** 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));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in a new issue