這樣應(yīng)該可以了
我們一直強調(diào)成都網(wǎng)站設(shè)計、網(wǎng)站制作對于企業(yè)的重要性,如果您也覺得重要,那么就需要我們慎重對待,選擇一個安全靠譜的網(wǎng)站建設(shè)公司,企業(yè)網(wǎng)站我們建議是要么不做,要么就做好,讓網(wǎng)站能真正成為企業(yè)發(fā)展過程中的有力推手。專業(yè)網(wǎng)站制作公司不一定是大公司,創(chuàng)新互聯(lián)作為專業(yè)的網(wǎng)絡(luò)公司選擇我們就是放心。
如果還有那個地方不懂的,建議你研究下漢諾塔算法
import
java.io.BufferedReader;//引入IO包中的BufferedReader
import
java.io.IOException;//引入IO包中的IO異常處理
import
java.io.InputStreamReader;//引入IO包中的InputStreaReader
public
class
Hinoi
{
//主類
static
int
m=0;//定義移動的次數(shù)
//主程序入口--main方法
public
static
void
main(String[]
args)
{
//創(chuàng)建BufferedReader對象,InputStream輸入流
BufferedReader
bf
=
new
BufferedReader(new
InputStreamReader(System.in));
System.out.println("請輸入盤子的個數(shù):");
try
{
int
sl
=
Integer.parseInt(bf.readLine().toString());//接收總盤子個數(shù)
toMove(sl,"A","B","C");//調(diào)用移動方法
A--C
}
catch
(NumberFormatException
e)
{捕獲NumberFormatException異常
//
TODO
Auto-generated
catch
block
e.printStackTrace();//打印異常
}
catch
(IOException
e)
{//捕獲IOException異常
//
TODO
Auto-generated
catch
block
e.printStackTrace();//打印異常
}
System.out.println("總共移動了:"+m+"
次數(shù)");//打印移動次數(shù)
}
//移動方法
private
static
void
toMove(int
sl,
String
one,
String
two,String
three)
{
if(sl==1){//如果只有一個盤子,則直接移動到C柱
System.out.println("盤子"+sl+"
從
"+one+"----"+three);
}else{//如果總盤數(shù)大于1,則遞歸調(diào)用移動方法
//把所有的數(shù)量為sl-1的盤子全部從A移到到B(C作為一個過渡),好提供一個最下面的位置給最大盤子到C;
toMove(sl-1,one,three,two);
System.out.println("盤子"+sl+"
從
"+one+"----"+three);
//把所有的剩余的盤子從B移動到C(A作為一個過渡)
toMove(sl-1,two,one,three);
}
m++;
}
}
附錄:主要源程序
(1) Disk.java
package code;
import java.awt.*;
public class Disk extends Button {
int number;//盤子的個數(shù)
public Disk(int number) {this.number = number;
setBackground(Color.yellow);}
public int getNumber() {return number; }}
(2) TowerPoint.java
package code;
import java.awt.*;
public class TowerPoint {
int x, y;//塔上的點位置,即盤子的放置位置
boolean isHaveDisk;//判斷點上是否有盤子
Disk disk ;HannoiTower con ;
public TowerPoint(int x, int y, boolean boo) {this.x = x; this.y = y; isHaveDisk = boo; }
public boolean getIsHaveDisk() {return isHaveDisk; }
public void setIsHaveDisk(boolean boo) {isHaveDisk = boo; }
public int getX() { return x; } //獲得點位置坐標
public int getY() { return y; }
public void putDisk(Disk disk, HannoiTower con) {//在點上放盤子
this.con = con;con.setLayout(null);//設(shè)置布局
this.disk = disk;con.add(disk);//加盤子到容器中
int w = disk.getBounds().width;//獲得盤子的長和寬 getBounds()以Rectangle對象的形式獲取組件的邊界
int h = disk.getBounds().height;
disk.setBounds(x - w / 2, y - h / 2, w, h);//setBounds()移動組件并調(diào)整其大小,控件位置坐標,后面是寬度和高度
isHaveDisk = true;con.validate(); }
public Disk getDisk() {return disk; }}
(3) HannoiTower.java
package code;
import javax.swing.*;
import java.awt.*;
public class HannoiTower extends JPanel{
TowerPoint point[];//塔上點數(shù)組
boolean move = false;//判斷是否移動
Disk disks[];//盤子數(shù)組
int diskNum = 0;//定義盤子個數(shù)
int width, height;//盤子的寬度和高度
char towerName[] = { 'A', 'B', 'C' };//塔名
TextArea infoArea ;
int autoNum = 1;//計算步數(shù)
public HannoiTower(int number, int w, int h, char[] name, TextArea text) {towerName = name;diskNum = number;width = w;height = h;
infoArea = text;setLayout(null);
disks = new Disk[diskNum];//初始化盤子個數(shù)
//設(shè)置塔上的點屬性
point = new TowerPoint[3 * diskNum];//塔上點的個數(shù)=3*盤子個數(shù)
int space = 20;
for (int i = 0; i diskNum; i++) {//第一根柱子上的點
point[i] = new TowerPoint(40 + width, 100 + space, false);//設(shè)置點的位置和沒有盤子
space = space + height; }
space = 20;
for (int i = diskNum; i 2 * diskNum; i++) {//第二根柱子上的點
point[i] = new TowerPoint(200 + width, 100 + space, false);
space = space + height; }
space = 20;
for (int i = 2 * diskNum; i 3 * diskNum; i++){//第三根柱子上的點
point[i] = new TowerPoint(360 + width, 100 + space, false);
space = space + height; }
//設(shè)置盤子屬性
int tempWidth = width;
int sub = (int) (tempWidth / diskNum);
for (int i = diskNum - 1; i = 0; i--) {disks[i] = new Disk(i);
disks[i].setSize(tempWidth, height);//設(shè)置盤子的寬和高
tempWidth = tempWidth - sub;}
for (int i = 0; i diskNum; i++) {point[i].putDisk(disks[i], this);
}}
public void paint(Graphics g) {super.paint(g);
g.drawLine(point[0].getX(), point[0].getY(), point[diskNum - 1].getX(),point[diskNum - 1].getY());//畫3根豎線
g.drawLine(point[diskNum].getX(), point[diskNum].getY(),
point[2 * diskNum - 1].getX(), point[2 * diskNum - 1].getY());
g.drawLine(point[2 * diskNum].getX(), point[2 * diskNum].getY(),
point[3 * diskNum - 1].getX(), point[3 * diskNum - 1].getY());
g.drawLine(point[diskNum - 1].getX() - width,
point[diskNum - 1].getY(), point[3 * diskNum - 1].getX()
+ width, point[3 * diskNum - 1].getY());
int leftx = point[diskNum - 1].getX() - width;//畫灰色矩形
int lefty = point[diskNum - 1].getY();
int w = (point[3 * diskNum - 1].getX() + width) - (point[diskNum - 1].getX() - width);
int h = height / 2;
g.setColor(Color.gray);
g.fillRect(leftx, lefty, w, h);
g.setColor(Color.red);//畫紅點
int size = 4;
for (int i = 0; i 3 * diskNum; i++) {
g.fillOval(point[i].getX() - size / 2, point[i].getY() - size / 2, size, size); }
g.drawString("" + towerName[0] + "塔", point[diskNum - 1].getX(),
point[diskNum - 1].getY() + 30);
g.drawString("" + towerName[1] + "塔", point[2 * diskNum - 1].getX(),
point[diskNum - 1].getY() + 30);
g.drawString("" + towerName[2] + "塔", point[3 * diskNum - 1].getX(),
point[diskNum - 1].getY() + 30);
g.drawString("將全部盤子從" + towerName[0] + "塔搬運到" + towerName[1] + "塔"+ towerName[2] + "塔", point[diskNum - 1].getX(),point[diskNum - 1].getY() + 80);}
/**
* 自動演示函數(shù)
*/
public void autoMoveDisk(int diskNum, char one, char two, char three) {//one塔1、two塔2、three塔3
if (diskNum == 1) //當(dāng)盤子只有一個時
{infoArea.append(autoNum + ":" + one + "塔 -----" + three + "塔\n");
autoNum++;
Disk disk = getTopDisk(one);//獲得塔1上最上面的盤子
int startI = getTopDiskPosition(one);//
int endI = getTopDiskUp(three);
if (disk != null) {point[endI].putDisk(disk, this);
point[startI].setIsHaveDisk(false);pause();}}
else {autoMoveDisk(diskNum - 1, one, three, two);
infoArea.append(autoNum + ":" + one + "塔 -----" + three + "塔\n");
autoNum++;
Disk disk = getTopDisk(one);
int startI = getTopDiskPosition(one);
int endI = getTopDiskUp(three);
if (disk != null) {point[endI].putDisk(disk, this);
point[startI].setIsHaveDisk(false);pause();}
autoMoveDisk(diskNum - 1, two, one, three);}}
/**
* 取最上方的盤子
*/
public Disk getTopDisk(char towerN) {//towerN塔名
Disk disk = null;
if (towerN == towerName[0]) {
for (int i = 0; i diskNum; i++) {
if (point[i].getIsHaveDisk() == true) {//判斷是否有盤子
disk = point[i].getDisk();break;}}}
if (towerN == towerName[1]) {
for (int i = diskNum; i 2 * diskNum; i++) {
if (point[i].getIsHaveDisk() == true) {
disk = point[i].getDisk();break;}}}
if (towerN == towerName[2]) {
for (int i = 2 * diskNum; i 3 * diskNum; i++) {
if (point[i].getIsHaveDisk() == true) {
disk = point[i].getDisk();break;}}}
return disk;}
/**
* 在塔中獲取盤子的放置位置
*/
public int getTopDiskUp(char towerN) {
int position = 0;
if (towerN == towerName[0]) {
int i = 0;
for (i = 0; i diskNum; i++) {
if (point[i].getIsHaveDisk() == true) {
position = Math.max(i - 1, 0);
break;}}
if (i == diskNum) {position = diskNum - 1; }}
if (towerN == towerName[1]) {
int i = 0;
for (i = diskNum; i 2 * diskNum; i++) {
if (point[i].getIsHaveDisk() == true) {
position = Math.max(i - 1, 0);break;}}
if (i == 2 * diskNum) {position = 2 * diskNum - 1; }}
if (towerN == towerName[2]) {int i = 0;
for (i = 2 * diskNum; i 3 * diskNum; i++) {
if (point[i].getIsHaveDisk() == true) {
position = Math.max(i - 1, 0);break;}}
if (i == 3 * diskNum) {position = 3 * diskNum - 1; }}
return position;}
/**
* 在塔中獲取最上面盤子的位置
*/
public int getTopDiskPosition(char towerN) {
int position = 0;
if (towerN == towerName[0]) {
int i = 0;
for (i = 0; i diskNum; i++) {
if (point[i].getIsHaveDisk() == true) {
position = i;break;}}
if (i == diskNum) {position = diskNum - 1; }}
if (towerN == towerName[1]) {int i = 0;
for (i = diskNum; i 2 * diskNum; i++) {
if (point[i].getIsHaveDisk() == true) {position = i;break;}}
if (i == 2 * diskNum) {position = 2 * diskNum - 1; }}
if (towerN == towerName[2]) {int i = 0;
for (i = 2 * diskNum; i 3 * diskNum; i++) {
if (point[i].getIsHaveDisk() == true) {
position = i;break;}}
if (i == 3 * diskNum) {position = 3 * diskNum - 1; }}
return position;}
public void pause() {
try {Thread.sleep(1000);// 1s移動1步} catch (InterruptedException e) {}}}
(4) Tower.java
package code;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Tower extends Frame implements ActionListener, ItemListener, Runnable {
HannoiTower tower;
JButton renew, auto;
Choice diskNumComBox;
char towerName[] = { 'A', 'B', 'C' };
int diskNum, diskWidth, diskHeight;
Thread thread;
TextArea infoArea;
public Tower() {
thread = new Thread(this);
diskWidth = 120;diskHeight = 18;
infoArea = new TextArea(15, 15);
infoArea.setText(null);
diskNumComBox = new Choice();//下拉列表
diskNumComBox.setName("diskNumComBox");//設(shè)置名字
diskNumComBox.setSize(300, 10);//設(shè)置列表大小
diskNumComBox.setFont(new java.awt.Font ("Dialog", 0, 11));//設(shè)置字體
diskNumComBox.setBackground(java.awt.Color.white);//設(shè)置下拉按鈕的背景色
diskNumComBox.setForeground(java.awt.Color.black);//設(shè)置下拉按鈕的前景色
for(int i=1;i=9;i++){diskNumComBox.add(String.valueOf(i));}//設(shè)置盤子數(shù)目
diskNum = Integer.valueOf(diskNumComBox.getSelectedItem().toString());
tower = new HannoiTower(diskNum, diskWidth, diskHeight, towerName, infoArea);
renew = new JButton("重新開始");
auto = new JButton("自動演示");
renew.addActionListener(this);
auto.addActionListener(this);
diskNumComBox.addItemListener(this);
JPanel topPanel = new JPanel();//設(shè)置兩個按鈕和下拉按鈕的布局,放于容器topPanel中
topPanel.add(auto, BorderLayout.WEST);
topPanel.add(renew, BorderLayout.CENTER);
topPanel.add(diskNumComBox, BorderLayout.EAST);
add(tower, BorderLayout.CENTER);//設(shè)置整體布局為邊界布局
add(topPanel, BorderLayout.NORTH);
add(infoArea, BorderLayout.EAST);
addWindowListener(new WindowAdapter() {//關(guān)閉窗口時調(diào)用
public void windowClosing(WindowEvent e) {
System.exit(0);}});
setVisible(true);setBounds(40, 20, 700, 540);
validate();//是Container類中的方法,該方法用來更新容器中的布局}
public void actionPerformed(ActionEvent e) {//重置
if (e.getSource() == renew) {
if (!(thread.isAlive())) {//判斷線程不活著
this.remove(tower);//Frame中的函數(shù),重新構(gòu)建,從此窗體移除指定的菜單欄。
infoArea.setText(null);
tower = new HannoiTower(diskNum, diskWidth, diskHeight, towerName, infoArea);
add(tower, BorderLayout.CENTER);
validate();}
else {}}
if (e.getSource() == auto) {//創(chuàng)建線程,自動演示
if (!(thread.isAlive())) {thread = new Thread(this); }
try {thread.start();} catch (Exception eee) {}}}
public void itemStateChanged(ItemEvent e) {
if (e.getSource() == diskNumComBox) {
if (!(thread.isAlive())) {
this.remove(tower);
infoArea.setText(null);
diskNum = Integer.valueOf(diskNumComBox.getSelectedItem().toString());
tower = new HannoiTower(diskNum, diskWidth, diskHeight, towerName, infoArea);
add(tower, BorderLayout.CENTER);
validate();}
else {}}}
public void run() {
this.remove(tower);
infoArea.setText(null);
tower = new HannoiTower(diskNum, diskWidth, diskHeight, towerName, infoArea);
add(tower, BorderLayout.CENTER);validate();
tower.autoMoveDisk(diskNum, towerName[0], towerName[1], towerName[2]);}
public static void main(String args[]) {
new Tower();}}
public?class?Hannoi?{
public?static?void?main(String[]?args)?{
int?nDisks?=?3;
moveDish(nDisks,?'A',?'B',?'C');
}
private?static?void?moveDish(int?level,?char?from,?char?inter,?char?to)?{
if?(level?==?1)?{
System.out.println("從"?+?from?+?"移動盤子?"?+?level?+?"?號到"?+?to);
}?else?{
moveDish(level?-?1,?from,?to,?inter);
System.out.println("從"?+?from?+?"移動盤子?"?+?level?+?"?號到"?+?to);
moveDish(level?-?1,?inter,?from,?to);
}
}
}