Java八皇后

package queen;

import java.awt.*;
import java.awt.event.*;

@SuppressWarnings("serial")
class equeen extends Frame implements ActionListener {
 // 构造界面和定义数组
 Button enter;
 Button clean;
 Button exit;
 int num[][]=new int[93][9];
 int i, j, q,cont=0;
 int b[] = new int[9];
 Label a[][] = new Label[9][9];
 equeen(String s) {
  GridLayout grid;
  grid = new GridLayout(9, 8);
  setLayout(grid);
  enter = new Button("begin");
  clean = new Button("clean");
  exit = new Button("esit");
  for (int i = 1; i < 9; i++) {
   for (int j = 1; j < 9; j++) {
    a[i][j] = new Label();
    if ((i + j) % 2 == 0)
     a[i][j].setBackground(Color.yellow);
    else
     a[i][j].setBackground(Color.gray);
    add(a[i][j]);
   }
  }
  add(enter);
  add(clean);
  add(exit);
  enter.addActionListener(this);
  clean.addActionListener(this);
  exit.addActionListener(this);
  setBounds(100, 100, 300, 300);
  // 大小
  setVisible(true);
  validate();
 }

 //判断函数
 public boolean find(int i,int k){
  int j;
  j=1;
  while(j<k){
   if((b[j]==i)||(Math.abs(b[j]-i)==Math.abs(j-k)))
    return false;
   j++;
  }
  return true;
 }
 
 void place(int k, int n){
  if(k>n){
   printf(n);
   
   //a[7][7].setText("K");//该88矩形框  是从 00开始的!!
  }
  else
   for(int i=1;i<=n;i++)
    if(find(i,k)){
     b[k]=i;
     place(k+1,n);
    }
  
 }
 
 void printf(int n)
 {
  cont++;
  int i;
  System.out.println("第"+cont+"个解");
  for(i=1;i<=n;i++){
   
   num[cont][i]=b[i];
   //q=b[i];
   //a[q][i].setText("K");
   //clean();
   System.out.print("--"+b[i]);
  }
  System.out.println();
  //for(i=1;i<=n;i++)
  //System.out.println("dddddd"+num[1][i]);
  
 }
 void clean(){
  for (int i = 1; i < 9; i++) {
   for (int j = 1; j < 9; j++) {
    a[i][j].setText("");
   }
  }
 }
 
 void write(){
  int w=(int)(Math.random()*93);
  for (int i = 1; i < 9; i++) {
   
  int c= num[w][i];
   a[c][i].setText("K");
  }
 }
 
 public void actionPerformed(ActionEvent e) {
  if (e.getSource() == enter) {
   clean();
   //a[7][7].setText("K");
   write();
  }
  if (e.getSource() == clean) {
   clean();
  }
  if (e.getSource() == exit) {
   System.exit(0);
  }
 }
}

class queen {
 public static void main(String[] args) {
  
  equeen a = new equeen("bbb");
  a.place(1, 8);
 }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值