HannonCode(0825)

 import java.util.*;
 import java.io.*;
 
 
 class Disk
 {
  private String name;
  private byte num;
  
  public Disk( byte num )
  {
   if( num < 0 )
   {
    throw new IllegalArgumentException("num can't lesson then 0");
   }
   
   this.num = num;
   
   StringBuilder sb = new StringBuilder( num*2 );  //预留一个字符空间
   
   for( byte i=0; i<num*2-1; i++)
   {
    sb.append("*");
   }
   
   name = sb.toString();
  }
  
  public String toString()
  {
   return name;
  }
  
  public byte getNum()
  {
   return num;
  }
 }
 
 
 
 class StatusObject
 {
  private byte num = 0;   //盘子个数
  private Stack<Disk> placeOne   = new Stack<Disk>();
  private Stack<Disk> placeTwo   = new Stack<Disk>();
  private Stack<Disk> placeThree = new Stack<Disk>();
  
  public StatusObject( byte num )
  {
   if( num < 0 )
   {
    throw new IllegalArgumentException("num < 0!");
   }
   
   this.num = num;
   
   for(int i=num; i>=1; i--)
   {
    placeOne.push( new Disk((byte)i) );
   } 
  }
  
  public void move( byte from , byte to )
  {
   Stack[] stk = { placeOne , placeTwo , placeThree };
   stk[to].push( (Disk)stk[from].pop() );
  }
  
  public void printStatus( PrintStream out )
  {
   Disk[] p1 = new Disk[ placeOne.size() ];
   Disk[] p2 = new Disk[ placeTwo.size() ];
   Disk[] p3 = new Disk[ placeThree.size() ];
   
   p1 = placeOne.toArray(p1);
   p2 = placeTwo.toArray(p2);
   p3 = placeThree.toArray(p3);
   
   for( int i=num-1; i>=0; i--)
   {
    String s1 = ( i >= p1.length ? "" : p1[i].toString());
    String s2 = ( i >= p2.length ? "" : p2[i].toString());
    String s3 = ( i >= p3.length ? "" : p3[i].toString());
    
    out.printf("/t%10s/t/t%10s/t/t%10s/t",s1,s2,s3);
    out.println();
   }
   out.println("---------------------------------------------------"+
         "------------------------");
  }
 }
 
 
 public class Hannon
 {
  public static StatusObject status;
  
  public static void hannon( int num , int from , int use , int to , StatusObject status)
  {
   if( num == 1 )
   {
    status.move((byte)from,(byte)to);
    status.printStatus( System.out );
   }
   else
   {
    hannon( num-1 , from , to , use ,status);
    status.move((byte)from,(byte)to);
    status.printStatus( System.out );
    hannon( num-1 , use  , from , to ,status);
   }
  }
 
  public static void main(String [] args) throws Exception //暂时不处理
  {
   final int num = 3;   //3个盘子
   
   if( args.length > 0)
   {
    File f = new File( args[0] );
    
    if( !f.exists() )
    {
     f.createNewFile();
    }
    
    System.setOut( new PrintStream( f ) );
   }
   
   status = new StatusObject((byte)num);     //设定状态物件支持的盘子数
   hannon( num , 0 , 1 , 2 , status);    //由0柱子通过1柱子搬到2柱子
  }
 } 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值