首頁>Club>
7
回覆列表
  • 1 # 使用者6353121943722

    public class Queen {

    private char[][] matrix;

    private int size;

    private int[] position;

    private int result;

    public int getResult() {

    return result;

    }

    public Queen(int size) {

    this.size = size;

    matrix = new char[size][size];

    for (int i = 0; i < size; i++) {

    for (int j = 0; j < size; j++) {

    matrix[i][j] = ‘x‘;

    }

    }

    position = new int[size];

    }

    private void printMatrix() {

    System.out.printf("---- sulution %d ----\n", result);

    for (int i = 0; i < size; i++) {

    System.out.print("{");

    for (int j = 0; j < size - 1; j++)

    System.out.print(matrix[i][j] + " ");

    System.out.print(matrix[i][size - 1]);

    System.out.println("}");

    }

    }

    private boolean isValid(int row, int col) {

    for (int i = 0; i < row; i++) {

    if (position[i] == position[row]) {

    return false;

    }

    if (Math.abs(position[i] - position[row]) == row - i) {

    return false;

    }

    }

    return true;

    }

    public void trial(int row) {

    for (int i = 0; i < size; i++) {

    matrix[row][i] = ‘.‘;

    position[row] = i;

    if (isValid(row, position[row])) {

    if (row < size - 1) {

    trial(row + 1);

    } else {

    /* success */

    result++;

    printMatrix();

    }

    }

    matrix[row][i] = ‘x‘;

    }

    }

    public static void main(String[] args) {

    Queen test = new Queen(4);

    test.trial(0);

    System.out.printf("result is: %d", test.getResult());

    }

    }

  • 中秋節和大豐收的關聯?
  • 描寫古代房間的句子?