Reputation: 91
Tower of Hanoi problem :
You have 3 towers and N disks of different sizes which can slide onto any tower.
The puzzle starts with disks sorted in ascending order of size from top to bottom (i.e., each disk sits on top of an even larger one). You have the following constraints:
(1) Only one disk can be moved at a time.
(2) A disk is slid off the top of one tower onto the next rod.
(3) A disk can only be placed on top of a larger disk. Write a program to move the disks from the first tower to the last using Stacks.
Question : Why do we need a second/buffer/intermediate stack ?
I have solved this without using a buffer stack. I used the implicit stack created by method(recursion).
See code :
public void play(Stack<Integer> aSourceStack,Stack<Integer> aTargetStack){
if(aSourceStack.isEmpty()){
return;
}
Integer temp = aSourceStack.pop();
play(aSourceStack,aTargetStack);
aTargetStack.push(temp);
}
Also am I violating the second constraint : (2) A disk is slid off the top of one tower onto the next rod.
Does this mean that i can't store the plate in a temporary variable ? It has to go on stack only ?
If yes, then i think i have my answer and i can close the question.
Please confirm.
Upvotes: 0
Views: 289
Reputation: 77885
Let me search that for you ... this is a classic puzzle.
You are supposed to implement the solution using one instance of the Stack class for each tower. There are three towers, so you have three Stack instances. Yes, when you pop a disk off the top of one tower, you must immediately push it onto the next tower. An appropriate statement might be
aTargetStack.push(aSourceStack.pop())
The code you wrote does not solve the problem; it tosses each disk in turn into the air, and then shoves them onto the target stack in the desired order: N disks in N moves. A correct, ideal solution will take 2^N-1 moves.
Upvotes: 3