编辑代码

public class EightQueens {

    private static final int BOARD_SIZE = 8;
    private int[] queens;

    public EightQueens() {
        queens = new int[BOARD_SIZE];
        solve(0);
    }

    private void solve(int row) {
        if (row == BOARD_SIZE) {
            printSolution();
            return;
        }

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

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

    private void printSolution() {
        for (int i = 0; i < BOARD_SIZE; i++) {
            for (int j = 0; j < BOARD_SIZE; j++) {
                System.out.print(queens[i] == j ? "Q " : ". ");
            }
            System.out.println();
        }
        System.out.println();
    }

    public static void main(String[] args) {
        new EightQueens();
    }
}