汉诺塔的Java 源程序

博客展示了用Java实现汉诺塔问题的代码,设置了盘子数量和柱子标识,通过递归方法输出汉诺塔移动步骤和总步数。同时强调递归需具备不符合递归的条件、递归主体限制条件及递归主体这三个要素,还提及斐波那契数列等经典递归程序。

刚写的:

package mooonsoft.j2se;

public class Hannoi
{
  public Hannoi()
  {
  }
  public static void main(String args[])
  {
  //set plates number
  int plates=2;
  //set the zhuzhi
  String A="A", B="B", C="C";
 
  System.out.println("the plates number is "+plates);
  System.out.println("Hannoi 's method path is ");
 
  hannio(plates, A,B, C);
  //print hannoi 's step
  System.out.println(" Total steps is "+totalSteps);
   
  }
  public static void hannio(int plates, String A, String B, String C)
  {
  
    if(plates==1)
    {
    System.out.println("Step:"+A+"-->"+C);
    totalSteps++;
   
    }
    else if(plates>1)
    {
    hannio(plates-1, A, C, B);
    System.out.println("Step:"+A+"-->"+C);
     
    hannio(plates-1,B, A, C);
     totalSteps++;
 
    }
  }
   private static int totalSteps=0;
}

注意递归的三个要素:

1)写一个不符合递归的条件

2)递归主体的限制条件,什么条件下调用自身

3)递归主体

缺一不可!

递归比较经典的程序,菲波那契数列,阶层,汉诺塔

Java语言编写的汉诺塔程序,形象直观; import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Tower extends Frame implements ActionListener,Runnable { HannoiTower tower=null; Button renew,auto=null; char towerName[]={'A','B','C'}; int 盘子数目,盘宽,盘高; Thread thread; TextArea 信息条=null; public Tower() { thread=new Thread(this); 盘子数目=5; 盘宽=80; 盘高=18; 信息条=new TextArea(12,12); 信息条.setText(null); tower=new HannoiTower(盘子数目,盘宽,盘高,towerName,信息条); renew=new Button("重新开始"); auto=new Button("自动演示搬盘子"); renew.addActionListener(this); auto.addActionListener(this); add(tower,BorderLayout.CENTER); add(renew,BorderLayout.SOUTH); add(auto,BorderLayout.NORTH); add(信息条,BorderLayout.EAST); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); setVisible(true); setBounds(60,20,670,540); validate(); } public void actionPerformed(ActionEvent e) { if(e.getSource()==renew) { if(!(thread.isAlive())) { this.remove(tower); 信息条.setText(null); tower=new HannoiTower(盘子数目,盘宽,盘高,towerName,信息条); add(tower,BorderLayout.CENTER); validate(); } else { } } if(e.getSource()==auto) { if(!(thread.isAlive())) { thread=new Thread(this); } try { thread.start(); } catch(Exception eee) { } } } public void run() { this.remove(tower); 信息条.setText(null); tower=new HannoiTower(盘子数目,盘宽,盘高,towerName,信息条); add(tower,BorderLayout.CENTER); validate(); tower.自动演示搬运盘子(盘子数目,towerName[0] ,towerName[1],towerName[2]); } public static void main(String args[]) { new Tower(); } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值