题目:
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) {
res.clear();
memset(used, false, sizeof(used));
dfs(0, n);
return res;
}
private:
vector<vector<string> > res;
// a[i]表示第i行的a[i]列有Queen
int a[100];
int used[100];
void dfs(int dep, int maxDep) {
if (dep == maxDep) {
vector<string> ans;
for (int i = 0; i < maxDep; i++) {
string s;
int j;
for (j = 0; j < a[i]; j++)
s += '.';
s += 'Q';
j++;
while (j != maxDep) {
s += '.';
j++;
}
ans.push_back(s);
}
res.push_back(ans);
return;
}
for (int y = 0; y < maxDep; y++) {
if (check(dep, y) && !used[y]) {
used[y] = true;
a[dep] = y;
dfs(dep + 1, maxDep);
used[y] = false;
}
}
}
bool check(int x, int y) {
for (int i = 0; i < x; i++) {
if (abs(i-x) == abs(y-a[i]))
return false;
}
return true;
}
};