编辑代码

#include <iostream>
#include <vector>
using namespace std;

const int M = 8;
int n = 0;

// 判断皇后落点是否合法
bool check(vector<vector<bool> > &matrix, int row, int column) {
    if (row == 0) {
        return true;
    }
    int i, j;
    // 纵向判断
    for (i = 0; i < row; i++) {
        if (matrix[i][column]) {
            return false;
        }
    }
    i = row - 1;
    j = column - 1;
    // 正斜对角线
    while (i >= 0 && j >= 0) {
        if (matrix[i][j]) {
            return false;
        }
        i--, j--;
    }

    i = row - 1;
    j = column + 1;
    // 负斜对角线
    while (i >= 0 && j < M) {
        if (matrix[i][j]) {
            return false;
        }
        i--, j++;
    }
    return true;
}

// 输出结果
void output(vector<vector<bool> > &matrix) {
    n++;
    cout << "*********************************************" << endl;
    for (int i = 0; i < M; i++) {
        for (int j = 0; j < M; j++) {
            cout << matrix[i][j] << " ";
        }
        cout << endl;
    }
    cout << "*********************************************" << endl;
}

void eightQueen(vector<vector<bool> > &matrix, int row) {
    for (int column = 0; column < M; column++) {
        // 放置皇后
        matrix[row][column] = true;
        // 递归下一行
        if (check(matrix, row, column)) {
            if (row + 1 == M) {
                output(matrix);
            } else {
                eightQueen(matrix, row + 1);
            }
        }
        // 回溯,撤销当前选择
        matrix[row][column] = false;
    }
}

int main() {
    vector<vector<bool> > matrix(M, vector<bool>(M, false));
    eightQueen(matrix, 0);
    cout << n << "种解" << endl;
    system("pause");
    return 0;
}