1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| import java.util.Stack;
class Ho { public static void main(String args[]) { int n = 5;
String sName[] = new String[4]; sName[0] = "C"; sName[1] = "A"; sName[2] = "B"; sName[3] = "C";
Stack s = new Stack(); s.push(new Integer(n)); s.push(new Integer(1)); s.push(new Integer(3)); s.push(new Integer(0));
while(!s.empty()) { Object processed = s.pop(); Object to = s.pop(); Object from = s.pop(); n = Integer.parseInt(s.pop().toString()); int left = 6 - Integer.parseInt(from.toString()) - Integer.parseInt(to.toString());
if (Integer.parseInt(processed.toString()) == 0) { if (n == 1) { System.out.println("Move disk " + n + " from " + sName[Integer.parseInt(from.toString())] + " to " + sName[Integer.parseInt(to.toString())]); }else{ s.push(new Integer(n)); s.push(new Integer(Integer.parseInt(from.toString()))); s.push(new Integer(Integer.parseInt(to.toString()))); s.push(new Integer(1)); s.push(new Integer(n - 1)); s.push(new Integer(Integer.parseInt(from.toString()))); s.push(new Integer(left)); s.push(new Integer(0)); } }else{ System.out.println("Move disk " + n + " from " + sName[Integer.parseInt(from.toString())] + " to " + sName[Integer.parseInt(to.toString())]); s.push(new Integer(n - 1)); s.push(new Integer(left)); s.push(new Integer(Integer.parseInt(to.toString()))); s.push(new Integer(0)); } } } }
|