From 415068bc214902da2cd75eaf0fe4a68d2ceadd4a Mon Sep 17 00:00:00 2001 From: Aditya Date: Tue, 13 Sep 2022 19:25:58 +0530 Subject: [PATCH] towers of hanoi --- java/Stack/TOH.java | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 java/Stack/TOH.java diff --git a/java/Stack/TOH.java b/java/Stack/TOH.java new file mode 100644 index 0000000..8d11abb --- /dev/null +++ b/java/Stack/TOH.java @@ -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 S = new AStack(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)); + } + } +}