import java.util.Stack;
public class Demo {
public static void main(String[] args) {
// TODO Auto-generated method stub
int n=3;
int disks=5;
Tower[] towers= new Tower[ n];
for( int i=0; i< n; i++){
towers[ i]= new Tower( i);
}
for( int i= disks; i>=0; i--){
towers[0].add( i);
}
towers[0].moveDisks( disks, towers[2], towers[1]);
}
}
class Tower{
public Stack<Integer> disks;
public int index;
public Tower(int index){
disks= new Stack<Integer>();
this. index= index;
}
public int getIndex(){
return this. index;
}
public void add(int d){
if(! disks.isEmpty()&& disks.peek()<= d)
System. out.println( "Error placing disk"+d);
else
disks.push( d);
}
//将orgin顶端的盘子移到destination
public void movetoTop(Tower t){
int top= disks.pop();
t.add( top);
System. out.println( "Move disk "+ top+ " from "+this.getIndex()+" to "+t.getIndex());
}
public void moveDisks( int n,Tower destination,Tower buffer){
if( n>0){
//将顶端n-1个盘子从origin移到buffer
moveDisks( n-1, buffer, destination);
this.movetoTop( destination);
//将顶部n-1个盘子从buffer移到destination,将origin用作缓冲区
buffer.moveDisks( n-1, destination, this);
}
}
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/shangqing1123/article/details/47278665