八皇后问题

问题的类别是回溯(backtrace).

回溯通常用递归实现。回溯中注意边界问题,避免越界。同时,剪枝可以减少case数量。

具体看leetcode这里

// .h
#ifndef AGORITHM_NQUEENS_H
#define AGORITHM_NQUEENS_H

#include 
#include 

class NQueens {
public:
    static void test_nqueens();

    static std::vector> solveNQueens(int n);

private:
    static void visit(std::vector> &vis, std::vector> &mat, int r, int c,
                      std::vector> &ans);


    static void generateAnswer(const std::vector> &mat, std::vector> &ans);
};
#endif //AGORITHM_NQUEENS_H
// .cpp
#include 
#include 
#include "NQueens.h"

using namespace std;

std::vector> NQueens::solveNQueens(int n) {
    vector> vis(4, vector(n * 2, 0));
    std::vector> ans;
    vector> mat(n, vector(n, 0));

    for (int i = 0; i < n; i++) {
        visit(vis, mat, 0, i, ans);
    }

//    int nAnswer = ans.size();

    return ans;
}

void NQueens::visit(std::vector> &vis, std::vector> &mat, int r, int c,
                    std::vector> &ans) {
    const int N = mat.size();

    if (!vis[0][r] && !vis[1][c] && !vis[2][r + c] && !vis[3][(r - c + 2 * N) % (2 * N)]) {
        // mark
        vis[0][r] = 1;  // kth row
        vis[1][c] = 1;  // mth column
        vis[2][r + c] = 1;
        vis[3][(r - c + 2 * N) % (2 * N)] = 1;
        mat[r][c] = 1;
        if (r == N - 1) {
            generateAnswer(mat, ans);
        } else {
            for (int j = 0; j < N; j++) {
                visit(vis, mat, r + 1, j, ans);
            }
        }

        vis[0][r] = 0;
        vis[1][c] = 0;
        vis[2][r + c] = 0;
        vis[3][(r - c + 2 * N) % (2 * N)] = 0;
        mat[r][c] = 0;
    }
}

void NQueens::generateAnswer(const std::vector> &mat, std::vector> &ans) {
    const int N = mat.size();
    std::vector vec;
    for (int i = 0; i < N; i++) {
        std::string s;
        for (int j = 0; j < N; j++) {
            if (mat[i][j]) {
                s += "Q";
            } else {
                s += ".";
            }
        }
        vec.emplace_back(s);
    }
    ans.emplace_back(vec);
}

void NQueens::test_nqueens() {
    int n;
    std::cin >> n;
    auto ans = solveNQueens(n);
    std::cout << "nanswer: " << ans.size() / 4 << std::endl;
    for (auto &an : ans) {
        for (const auto &s : an) {
            std::cout << s << "\n";
        }
        std::cout << std::endl;
    }
}

你可能感兴趣的:(八皇后问题)