[Leetcode 91] 51 N-Queens
Problem:
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.."] ]
Analysis:
Classic DFS problem. During the enumeration, we set the '.' to 'Q' level by level. So we don't need to judge whether there is level collision. We use a one-dimension array to keep track of whether a column has already contains a Queen. And for diagonal and anti-diagonal, we make use of the property that slope of diagonal elements is 1 and of anti-diagonal is -1 to find those positions to be checked and then check.
There are still many optimizations can be done to further improve the solution
Code:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 class Solution { 2 public: 3 int dim, *col; 4 vector<vector<string> > res; 5 6 vector<vector<string> > solveNQueens(int n) { 7 // Start typing your C/C++ solution below 8 // DO NOT write int main() function 9 dim = n; 10 res.clear(); 11 12 string s(n, '.'); 13 col = new int[n]; 14 vector<string> tmp; 15 for (int i=0; i<n; i++) { 16 col[i] = 0; 17 tmp.push_back(s); 18 } 19 20 dfs(tmp, 0); 21 22 delete [] col; 23 24 return res; 25 } 26 27 28 private: 29 void dfs(vector<string> &s, int r) { 30 if (r == dim) { 31 res.push_back(s); 32 return ; 33 } 34 35 for (int i=0; i<dim; i++) { 36 if (col[i] == 0 && isValid(s, r, i)) { 37 col[i] = 1; 38 s[r][i] = 'Q'; 39 dfs(s, r+1); 40 s[r][i] = '.'; 41 col[i] = 0; 42 } 43 } 44 } 45 46 47 bool isValid(vector<string> &s, int r, int c) { 48 for (int i=0; i<dim; i++) { 49 for (int j=0; j<dim; j++) { 50 if ((abs(i-r) == abs(j-c)) || abs(i-r) == -abs(j-c)) { 51 if (s[i][j] == 'Q') 52 return false; 53 } 54 } 55 } 56 57 return true; 58 } 59 };