Skip to content

Instantly share code, notes, and snippets.

@chouclee
Created June 28, 2014 08:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chouclee/97dbc195b1c92b7b1418 to your computer and use it in GitHub Desktop.
Save chouclee/97dbc195b1c92b7b1418 to your computer and use it in GitHub Desktop.
[CC150][3.4] In the classic problem of the Towers of Hanoi, you have 3 rods 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 (e.g., each disk sits on top of an even larger one). You have the following constraints: (1) Only one disk can be moved at a t…
// reference : http://hawstein.com/posts/3.4.html
import java.util.Stack;
public class Hanoi {
private Stack<Operation> stack;
private class Operation {
private int start;
private int end;
private String src;
private String bridge;
private String dst;
public Operation(int start, int end, String src, String bridge, String dst ) {
this.start = start;
this.end = end;
this.src = src;
this.bridge = bridge;
this.dst = dst;
}
}
public Hanoi(int start, int end ,String src, String bridge, String dst) {
stack = new Stack<Operation>();
stack.push(new Operation(start, end, src, bridge, dst));
Operation currentOp;
while (!stack.isEmpty()) {
currentOp = stack.pop();
if (currentOp.start != currentOp.end) {
stack.push(new Operation(currentOp.start, currentOp.end - 1,
currentOp.bridge, currentOp.src, currentOp.dst));
stack.push(new Operation(currentOp.end, currentOp.end,
currentOp.src, currentOp.bridge, currentOp.dst));
stack.push(new Operation(currentOp.start, currentOp.end - 1,
currentOp.src, currentOp.dst, currentOp.bridge));
}
else {
System.out.println("Move disk " + currentOp.start +
" from " + currentOp.src + " to " + currentOp.dst);
}
}
}
public static void main(String[] args) {
Hanoi test = new Hanoi(1, 4, "A", "temp", "B");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment