LeetCode 51. N-Queens

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

image

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.."]
]

典型的N皇后问题, 直接暴搜就可以了。

class Solution
{
    void dfs(vector<vector<string>> &ans, vector<string> &mp, vector<bool> &mk_col, vector<bool> &mk_l, vector<bool> &mk_r, int x, int &n)
    {
        if(x == n)
        {
            ans.push_back(mp);
            return ;
        }
        for(int i=0; i<n; ++ i)
        {
            if(mk_col[i] == false && mk_l[x-i+n] == false && mk_r[x+i] == false)
            {
                mp[x][i] = 'Q', mk_col[i] = true, mk_l[x-i+n] = true, mk_r[x+i] = true;
                dfs(ans, mp, mk_col, mk_l, mk_r, x+1, n);
                mp[x][i] = '.', mk_col[i] = false, mk_l[x-i+n] = false, mk_r[x+i] = false;
            }
        }
    }
public:
    vector<vector<string>> solveNQueens(int n)
    {
        vector<vector<string>> ans;
        vector<string> mp(n, string(n, '.'));
        vector<bool> mk_col(n, false), mk_l(n<<1, false), mk_r(n<<1, false);

        dfs(ans, mp, mk_col, mk_l, mk_r, 0, n);

        return ans;
    }
};
原文地址:https://www.cnblogs.com/aiterator/p/6666533.html