java 马的遍历_象棋中马的遍历

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;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值