queens.java

来自「Java程序设计实用教程源代码 本书源代码按章分别放置在不同的文件夹中,所有程」· Java 代码 · 共 37 行

JAVA
37
字号
import javax.swing.*;
public class Queens {
  int[] a = new int[8];
  int[] b = new int[15];
  int[] c = new int[15];
  int[][] Queen = new int[8][8];
  void next(int i) {
    for (int j = 0; j < 8; j++) {
      if (a[j] == 0 && b[i + j] == 0 && c[i - j + 7] == 0) {
        a[j] = b[i + j] = c[i - j + 7] = 1;
        Queen[i][j] = 1;
        if (i < 7)
          next(i + 1);
        else {
          String output = new String();
          for (int m = 0; m < 8; m++) {
            for (int n = 0; n < 8; n++)
              output += "     " + Queen[m][n] + "      ";
            output += "\n";
          } //对每种可能的情况以0、1表示(1表示皇后)输出
          JTextArea outputArea = new JTextArea();
          outputArea.setText(output);
          JOptionPane.showMessageDialog(null, outputArea,
                                        "One possible distribution ",
                                        JOptionPane.INFORMATION_MESSAGE);
        }
        a[j] = b[i + j] = c[i - j + 7] = Queen[i][j] = 0;
      }
    }
  }

  public static void main(String args[]) {
    Queens one = new Queens();
    one.next(0);
    System.exit(0);
  }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?