packagecn.test.termtest.uglynumber;importjava.awt.BorderLayout;importjava.awt.Color;importjava.awt.Font;importjava.awt.GridLayout;importjava.awt.event.ActionEvent;importjava.awt.event.ActionListener;importjavax.swing.JButton;importjavax.swing.JFrame;importjavax.swing.JLabel;importjavax.swing.JPanel;public class TestChess extends JFrame implementsActionListener {static JButton button[][]; //棋盘的按钮
static int boardSize; //棋盘大小(行数/列数)
static int count; //落子的顺序
static intobstacleNum;
JLabel promptLabel=new JLabel(); //提示信息标签//马走日子的偏坐标
static int dx[] = {1,2,2,1,-1,-2,-2,-1};static int dy[] = {2,1,-1,-2,-2,-1,1,2};public static voidmain(String[] args) {
boardSize=5;
TestChess testChess=newTestChess();
}publicTestChess() {
count=1;//定义font为微软雅黑,普通,12号
Font font =new Font("宋体",Font.PLAIN,12);this.setTitle("象棋中马的遍历");
JPanel p1=new JPanel(); //正式面板
p1.setLayout(new GridLayout(boardSize,boardSize)); //GridLayout为网格布局
button =new JButton[boardSize+1][boardSize+1];int n=1;for(int i=1;i<=boardSize;i++)for(int j=1;j<=boardSize;j++) {
button[i][j]=newJButton();
button[i][j].setActionCommand(String.valueOf(n++));//动作命令,并非按钮上面的字,区别是哪个按钮
button[i][j].setFont(font);
button[i][j].addActionListener(this);//添加监听
p1.add(button[i][j]);
}
button[1][1].setText("卒");
button[5][1].setText("卒");
obstacleNum=2;
add(p1,BorderLayout.CENTER);//面板添加到窗口当中
JPanel p2 =newJPanel();
promptLabel=newJLabel();
promptLabel.setForeground(Color.RED);
promptLabel.setText("提示:单击某一个按钮,作为马的起始位置");
p2.add(promptLabel);
add(p2,BorderLayout.SOUTH);
setSize(300,200);this.setLocationRelativeTo(null);
setVisible(true);
}public voidactionPerformed(ActionEvent e) {
String buttonKey=e.getActionCommand();int intKey =Integer.parseInt(buttonKey);int row =intKey /boardSize +1;int col= intKey%boardSize;
button[row][col].setText("1");if(DFS(row,col))
promptLabel.setText("提示:遍历成功");elsepromptLabel.setText("提示:遍历失败");
}static boolean DFS(int x,inty) {//经过了所有的空位置
if(count == boardSize*boardSize-obstacleNum)return true;//遍历从当前点走日字能够到达的8个点
for(int dir =0;dir<8;dir++) {//走日字到达下一个点
int next_x =x+dx[dir];int next_y =y+dy[dir];//超出边界
if(next_x<1 || next_x > boardSize || next_y<1 || next_y>boardSize)continue;if(!button[next_x][next_y].getText().equals(""))continue;//访问过的点计数
count++;
button[next_x][next_y].setText(String.valueOf(count));if(DFS(next_x,next_y))return true;//从日字的一个对角线出发不能到达所有的位置
count--;//后退一步
button[next_x][next_y].setText("");
}return false;
}
}