Created
July 4, 2014 17:52
-
-
Save bitcpf/f13146e8c0283da3e4ba to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package cc150_3_4; | |
import java.util.Stack; | |
public class Hanoi { | |
public static void main(String[] args){ | |
Tower src = new Tower(3,0); | |
Tower dst = new Tower(0,1); | |
Tower via = new Tower(0,2); | |
System.out.println(src.stack.toString()); | |
src.moveDisk(dst,via,src.stack.size()); | |
System.out.println(dst.stack.toString()); | |
} | |
} | |
class Tower{ | |
Stack stack= new Stack(); | |
int idx; | |
public Tower(int n,int index){ | |
this.idx = index; | |
for(int i = n;i > 0; i--){ | |
stack.push(i); | |
} | |
} | |
public void moveTop(Tower dst){ | |
dst.stack.push(this.stack.pop()); | |
System.out.println("Move Top from tower "+idx + " to tower "+dst.idx); | |
} | |
public void moveDisk(Tower dst, Tower via, int size){ | |
if(size == 0) return; | |
moveDisk(via, dst, size - 1); | |
moveTop(dst); | |
via.moveDisk(dst, this, size-1); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment