编辑代码

#include <iostream>
#include <vector>

using namespace std;

const int N = 4; // 棋盘大小

// 检查在(row, col)位置放置皇后是否合法
bool isSafe(const vector<int>& board, int row, int col) {
    for (int i = 0; i < row; ++i) {
        if (board[i] == col ||        // 同一列
            board[i] - i == col - row ||  // 同一主对角线
            board[i] + i == col + row)    // 同一副对角线
        {
            return false;
        }
    }
    return true;
}

// 打印棋盘
void printBoard(const vector<int>& board) {
    for (int i = 0; i < N; ++i) {
        for (int j = 0; j < N; ++j) {
            if (board[i] == j) {
                cout << "Q ";
            } else {
                cout << ". ";
            }
        }
        cout << endl;
    }
    cout << endl;
}

// 回溯算法
void solveNQueens(vector<int>& board, int row, vector<vector<int> >& solutions) {
    if (row == N) {
        // 找到一个解决方案
        solutions.push_back(board);
        return;
    }

    for (int col = 0; col < N; ++col) {
        if (isSafe(board, row, col)) {
            board[row] = col; // 在当前行的合法位置放置皇后
            solveNQueens(board, row + 1, solutions); // 递归进入下一行
            board[row] = -1; // 回溯,尝试其他位置
        }
    }
}

int main() {
    vector<vector<int> > solutions; // 存储所有解决方案
    vector<int> board(N, -1); // 初始化棋盘

    solveNQueens(board, 0, solutions);

    // 打印所有解决方案
    for (vector<vector<int> >::iterator it = solutions.begin(); it != solutions.end(); ++it) {
        cout << "Solution " << distance(solutions.begin(), it) + 1 << ":\n";
        printBoard(*it);
    }

    // 打印解法总数
    cout << "Total solutions: " << solutions.size() << endl;

    return 0;
}