编辑代码

public class EightQueens {

    static final int N = 8; // 棋盘大小
    static int[] queens = new int[N]; // 皇后所在位置的列索引

    static void placeQueens(int row) {
        if (row == N) {
            printQueens();
            return;
        }
        for (int col = 0; col < N; col++) {
            if (isValid(row, col)) {
                queens[row] = col;
                placeQueens(row + 1);
            }
        }
    }

    static boolean isValid(int row, int col) {
        for (int i = 0; i < row; i++) {
            if (queens[i] == col || queens[i] - col == i - row || queens[i] - col == row - i) {
                return false;
            }
        }
        return true;
    }

    static void printQueens() {
        for (int row = 0; row < N; row++) {
            for (int col = 0; col < N; col++) {
                if (queens[row] == col) {
                    System.out.print("O");
                } else {
                    System.out.print("X");
                }
            }
            System.out.println();
        }
        System.out.println();
    }

    public static void main(String[] args) {
        placeQueens(0);
    }
}