编辑代码

public class EightQueens {
    private static final int BOARD_SIZE = 8;

    // queens数组用于记录每一行皇后所在的列
    private int[] queens = new int[BOARD_SIZE];

    // 记录所有解决方案的数量
    private int solutionCount = 0;

    // 主函数,调用 solve 方法解决问题
    public static void main(String[] args) {
        EightQueens solver = new EightQueens();
        solver.solve();
    }

    // 解决八皇后问题的方法
    public void solve() {
        placeQueens(0); // 从第一行开始放置皇后
        System.out.println("总共有 " + solutionCount + " 种解决方案。");
    }

    // 递归回溯的核心方法
    private void placeQueens(int row) {
        if (row == BOARD_SIZE) {
            // 找到一种解决方案
            printSolution();
            solutionCount++;
            return;
        }

        for (int col = 0; col < BOARD_SIZE; col++) {
            if (isValidPlacement(row, col)) {
                // 在当前位置放置皇后
                queens[row] = col;
                // 继续下一行的放置
                placeQueens(row + 1);
            }
            // 回溯,尝试下一列
        }
    }

    // 检查当前位置是否合法
    private boolean isValidPlacement(int row, int col) {
        for (int prevRow = 0; prevRow < row; prevRow++) {
            int prevCol = queens[prevRow];
            // 检查是否在同一列或同一对角线上
            if (col == prevCol || Math.abs(row - prevRow) == Math.abs(col - prevCol)) {
                return false;
            }
        }
        return true;
    }

    // 打印一种解决方案
    private void printSolution() {
        System.out.println("解决方案 " + solutionCount + ":");
        for (int row = 0; row < BOARD_SIZE; row++) {
            for (int col = 0; col < BOARD_SIZE; col++) {
                System.out.print(queens[row] == col ? "Q " : ". ");
            }
            System.out.println();
        }
        System.out.println();
    }
}