编辑代码

public class NQueens {

    private static final int N = 4;

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

    private static void solveNQueens() {
        int[][] board = new int[N][N];
        if (!solveNQueensUtil(board, 0)) {
            System.out.println("There is no solution");
        }
    }

    private static boolean solveNQueensUtil(int[][] board, int row) {
        if (row == N) {
            // 找到一个解决方案
            printSolution(board);
            return true;
        }

        boolean res = false;
        for (int i = 0; i < N; i++) {
            if (isSafe(board, row, i)) {
                // 在当前位置放置皇后
                board[row][i] = 1;

                // 递归到下一行
                res = solveNQueensUtil(board, row + 1) || res;

                // 回溯,撤销当前行的选择
                board[row][i] = 0;
            }
        }

        return res;
    }

    private static boolean isSafe(int[][] board, int row, int col) {
        // 检查同一列是否有皇后
        for (int i = 0; i < row; i++) {
            if (board[i][col] == 1) {
                return false;
            }
        }

        // 检查左上到右下的对角线
        for (int i = row, j = col; i >= 0 && j >= 0; i--, j--) {
            if (board[i][j] == 1) {
                return false;
            }
        }

        // 检查左下到右上的对角线
        for (int i = row, j = col; i >= 0 && j < N; i--, j++) {
            if (board[i][j] == 1) {
                return false;
            }
        }

        return true;
    }

    private static void printSolution(int[][] board) {
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++) {
                System.out.print(board[i][j] + " ");
            }
            System.out.println();
        }
        System.out.println();
    }
}