# #33 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.

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.

Example

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

[
// Solution 1
[".Q..",
"...Q",
"Q...",
"..Q."
],
// Solution 2
["..Q.",
"Q...",
"...Q",
".Q.."
]
]

Mycode（AC = 169ms）：

class Solution {
public:
/**
* Get all distinct N-Queen solutions
* @param n: The number of queens
* @return: All distinct solutions
* For example, A string '...Q' shows a queen on forth position
*/
vector<vector<string> > solveNQueens(int n) {
// write your code here
vector<vector<string>> ans;
if (n == 0) return ans;

vector<string> sofar;
unordered_set<int> col, diag;
solveNQueens(ans, sofar, n, col, diag);
return ans;
}

void solveNQueens(vector<vector<string>>& ans,
vector<string>& sofar,
int n,
unordered_set<int>& col,
unordered_set<int>& diag)
{
if (sofar.size() == n) {
ans.push_back(sofar);
return;
}

string tmp = nDots(n);
for (int i = 0; i < n; i++) {
// if there is no Q in same row, col, and diag,
// then tmp could be a potential ans
if (col.find(i) == col.end() &&
!findDiag(diag, sofar.size(), i, n))
{
col.insert(i);
diag.insert(sofar.size() * n + i);
tmp[i] = 'Q';
sofar.push_back(tmp);

solveNQueens(ans, sofar, n, col, diag);

sofar.pop_back();
tmp[i] = '.';
diag.erase(sofar.size() * n + i);
col.erase(i);
}
}
}

// write n '.' in a line
string nDots(int n) {
string str = "";
for (int i = 0; i < n; i++) {
str += ".";
}
return str;
}

// check whether there is Q in diag
bool findDiag(unordered_set<int>& diag, int i, int j, int n) {
for (auto it = diag.begin(); it != diag.end(); it++) {
int row = *it / n;
int col = *it % n;

if (abs(row - i) == abs(col - j)) return true;
}

return false;
}
};


#### LeetCode --- 51. N-Queens

2015-03-07 10:46:41

#### 【Leetcode】：51. N-Queens 问题 in JAVA

2016-04-25 19:16:59

#### [leetcode-51]N-Queens(java)

2015-08-03 09:06:27

#### LeetCode 51. N-Queens和52. N-Queens II的位运算解法

2016-09-09 17:00:08

#### N-Queens -- LeetCode

2014-03-07 00:32:30

#### LeetCode51——N-Queens

2015-10-24 20:58:58

#### [数据结构]N-Queens Problem（recursion）

2016-03-30 18:31:53

#### LeetCode 52. N-Queens II（N皇后）

2016-05-21 06:27:12

#### 【LeetCode with Python】 N-Queens

2014-09-21 17:44:49

#### leetCode 51.N-Queens (n皇后问题) 解题思路和方法

2015-07-13 13:23:15