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

 

 1 class Solution {
 2 public:
 3     vector<vector<string>> solveNQueens(int n) {
 4         vector<bool> mark,have1,have2;
 5         vector<vector<string>> res;
 6         vector<int> a;
 7         mark.resize(n,false);
 8         have1.resize((n<<1)-1,false);
 9         have2.resize((n<<1)-1,false);
10         help(a,n,mark,have1,have2,res);
11         return res;
12     }
13     void help(vector<int> &a,int n,vector<bool> &mark,vector<bool> &have1,vector<bool> &have2,vector<vector<string>> &res)
14     {
15         if(a.size()>=n)
16         {
17             vector<string> v;
18             for(int i=0;i<n;i++)
19             {
20                 string s="";
21                 for(int j=0;j<n;j++)
22                     s+=(j==a[i])?"Q":".";
23                 v.push_back(s);
24             }
25             res.push_back(v);
26             return;
27         }
28         for(int i=0;i<n;i++)
29         {
30             if((!mark[i])&&(!have1[i+a.size()])&&(!have2[i-a.size()+n-1]))
31             {
32                 mark[i]=have1[i+a.size()]=have2[i-a.size()+n-1]=true;
33                 a.push_back(i);
34                 help(a,n,mark,have1,have2,res);
35                 a.pop_back();
36                 mark[i]=have1[i+a.size()]=have2[i-a.size()+n-1]=false;
37             }
38         }
39     }
40 };