Iterative Code for Towers of Hanoi
So are you up for the challenge? Of course you are! We have to figure out an iterative solution.
The best thing we can do is define a stack for source
, destination
, intermediate
and N
. You can see that steps 1, 2, and 3 of the recursive case have to be executed in the same order.
This means we first push whatever corresponds to step 3 (to be executed last). Next, we push whatever corresponds to step 2 of the recursive case. Lastly, push whatever corresponds to step 1 of the recursive case.
This is typically how you would approach the solution of a recursive solution via iteration using a temporary stack. So here is a very elegant iterative
solution for Towers of Hanoi
.
xxxxxxxxxx
54
h.solve(3, 'A', 'B', 'C');
class HanoiIterative {
constructor() {
this.sourceStack = [];
this.destinationStack = [];
this.intermediateStack = [];
this.NStack = [];
}
​
shift(shelf1, shelf2) {
console.log("Shift from " + shelf1 + " to " + shelf2);
}
​
pushStacks(s, d, i, n) {
this.sourceStack.push(s);
this.destinationStack.push(d);
this.intermediateStack.push(i);
this.NStack.push(n);
}
​
popStacks() {
this.sourceStack.pop();
this.destinationStack.pop();
this.intermediateStack.pop();
this.NStack.pop();
}
​
solve(N, source, destination, intermediate) {
if (N <= 0)
return;
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment