汉诺塔(Tower of Hanoi),又称河内塔,是一个源于印度古老传说的益智玩具。大梵天创造世界的时候做了三根金刚石柱子,在一根柱子上从下往上按照大小顺序摞着64片黄金圆盘。大梵天命令婆罗门把圆盘从下面开始按大小顺序重新摆放在另一根柱子上。并且规定,在小圆盘上不能放大圆盘,在三根柱子之间一次只能移动一个圆盘。
改代码实现了汉诺塔的递归解法并通过图形化界面展示,如下图:
界面
结果
Hanoi代码
import java.awt.*;
public class Hanoi extends Panel {
public int[] poleA,poleB,poleC;
public int ln;
public String message="";
public Hanoi(int n){
ln=n;
poleA=new int[n+1];
poleB=new int[n+1];
poleC=new int[n+1];
for(int i=0;i<=n;i++) {
poleA[i]=n-i;
}
}
public void paint(Graphics g){
g.drawString(message,95,20);
g.drawString("A", 95, 200);
g.drawString("B", 195, 200);
g.drawString("C", 295, 200);
paintStack(poleA,g,100,180);
paintStack(poleB,g,200,180);
paintStack(poleC,g,300,180);
}
private void paintStack(int[] stk,Graphics g, int x, int y){
int i=0;
for(i=0;i<stk.length;i++) {
if(stk[i]!=0) {
g.fillRect(x-4*stk[i], y, 8*stk[i], 9);
y = y-10;
}
}
}
public void move(int n,int[] start,int[] end) {
end[ln-n]=start[ln-n];
start[ln-n]=0;
this.update(getGraphics());
this.paint(getGraphics());
try {
Thread.sleep(30);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void moveDish(int n,int[] start,int[] m,int[] end){
if(n==1) {
move(n,start,end);
}else {
moveDish(n-1,start,end,m);
move(n,start,end);
moveDish(n-1,m,start,end);
}
}
}
HanoiFrame代码
import java.awt.*;
import java.awt.event.*;
public class HanoiFrame extends Frame implements ActionListener{
public static void main(String[] args) {
HanoiFrame world = new HanoiFrame();
world.setVisible(true);
world.setResizable(false);
}
Hanoi h;
Button init,begin;
Panel panel;
TextField in;
public HanoiFrame(){
Label lb1=new Label("盘数");
init = new Button("开始");
init.addActionListener(this);
begin = new Button("移动");
begin.addActionListener(this);
in = new TextField(3);
panel = new Panel();
panel.add(lb1);
panel.add(in);
panel.add(init);
panel.add(begin);
this.add(panel,BorderLayout.SOUTH);
setSize(400,300);
setTitle("汉诺塔 递归实现");
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.out.println("系统退出!");
System.exit(1);
}
});
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() instanceof Button) {
Button bt=(Button)e.getSource();
if(bt==init&& in.getText()!=null) {
int n =Integer.parseInt(in.getText());
if(n>0&&n<=10) {
h=new Hanoi(n);
h.message="盘数为:"+n+"盘";
this.add(h, BorderLayout.CENTER);
setSize(400,301);
}else {
System.out.println("盘数太大,不好容纳");
}
}
if(bt==begin && in.getText()!=null){
int n =Integer.parseInt(in.getText());
h.moveDish(n,h.poleA,h.poleB,h.poleC);
in.setText(null);
in.setEditable(false);
}
}
}
}