Leetcode 51 N-Queens

来源:互联网 发布:python黑客 渗透技术 编辑:程序博客网 时间:2024/06/05 19:31

The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.

Given an integer n, return all distinct solutions to the n-queens puzzle.

Each solution contains a distinct board configuration of the n-queens’ placement, where ‘Q’ and ‘.’ both indicate a queen and an empty space respectively.

For example,
There exist two distinct solutions to the 4-queens puzzle:

[
[“.Q..”, // Solution 1
“…Q”,
“Q…”,
“..Q.”],

[“..Q.”, // Solution 2
“Q…”,
“…Q”,
“.Q..”]
]

class Solution {public:    vector<vector<string>> solveNQueens(int n) {        vector<vector<string> > ret;        vector<string> ans;        vector<size_t> colFlag;        recurve(ret, ans, colFlag, n);        return ret;    }private:    void recurve(vector<vector<string> >& ret, vector<string>& ans, vector<size_t>& colFlag, int n) {        size_t nrow = ans.size();        if(nrow == n) {            ret.push_back(ans);            return;        }        // [0 - n + 1]        // dummy head and dummy tail        // make flag        vector<size_t> flag(n, 0);        for (size_t j = 0; j != nrow; ++j) {            if (colFlag[j] + (nrow - j) < n)                flag[colFlag[j] + (nrow - j)] = 1;            // size_t < 0 溢出            if (static_cast<int>(colFlag[j]- (nrow - j)) > -1)                flag[colFlag[j] - (nrow - j)] = 1;            flag[colFlag[j]] = 1;        }        for (size_t i = 0; i != n; ++i) {            if (flag[i] == 0) {                string tmp(n, '.');                tmp[i] = 'Q';                ans.push_back(tmp);                colFlag.push_back(i);                recurve(ret, ans, colFlag, n);                colFlag.pop_back();                ans.pop_back();            }        }        return;    }};