编辑代码

public class EightQueens {
    private static final int SIZE = 8; // 棋盘大小
    private static int[] queens; // 皇后所在列的索引

    public static void main(String[] args) {
        queens = new int[SIZE];
        solve(0);
    }

    private static void solve(int row) {
        if (row == SIZE) {
            printQueens();
            return;
        }

        for (int col = 0; col < SIZE; col++) {
            if (isValid(row, col)) {
                queens[row] = col;
                solve(row + 1);
            }
        }
    }

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

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