编辑代码

#include <iostream>

const int MAX_N = 10; // Adjust the maximum value as needed

bool isCorrectColumn(int col, int curRow, int queueCount, int path[MAX_N]) {
    int leftup = col - 1;
    int rightup = col + 1;

    for (int i = curRow - 1; i >= 0; --i) {
        if (path[i] == col || (leftup >= 0 && path[i] == leftup) || (rightup < queueCount && path[i] == rightup)) {
            return false;
        }
        --leftup;
        ++rightup;
    }
    return true;
}

void findQueuePos(int queueCount, int curRow, int path[MAX_N], int solutions[MAX_N][MAX_N], int& solutionCount) {
    if (queueCount == curRow) {
        for (int i = 0; i < queueCount; ++i) {
            solutions[solutionCount][i] = path[i];
        }
        ++solutionCount;
        return;
    }

    for (int i = 0; i < queueCount; ++i) {
        if (isCorrectColumn(i, curRow, queueCount, path)) {
            path[curRow] = i;
            findQueuePos(queueCount, curRow + 1, path, solutions, solutionCount);
        }
    }
}

void solveQueueProblem(int queueCount) {
    int solutions[MAX_N][MAX_N];
    int path[MAX_N];
    int solutionCount = 0;

    findQueuePos(queueCount, 0, path, solutions, solutionCount);

    std::cout << "皇后问题有" << solutionCount << "种解决方案:" << std::endl;
    for (int s = 0; s < solutionCount; ++s) {
        for (int i = 0; i < queueCount; ++i) {
            for (int j = 0; j < queueCount; ++j) {
                if (j == solutions[s][i]) {
                    std::cout << 'O';
                } else {
                    std::cout << '.';
                }
            }
            std::cout << std::endl;
        }
        std::cout << std::endl;
    }
}

int main() {
    int queueCount = 8; // Change this to the desired number of queens
    solveQueueProblem(queueCount);

    return 0;
}