forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.cpp
27 lines (27 loc) · 818 Bytes
/
Solution.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
public:
vector<vector<string>> solveNQueens(int n) {
vector<int> col(n);
vector<int> dg(n << 1);
vector<int> udg(n << 1);
vector<vector<string>> ans;
vector<string> t(n, string(n, '.'));
function<void(int)> dfs = [&](int i) -> void {
if (i == n) {
ans.push_back(t);
return;
}
for (int j = 0; j < n; ++j) {
if (col[j] + dg[i + j] + udg[n - i + j] == 0) {
t[i][j] = 'Q';
col[j] = dg[i + j] = udg[n - i + j] = 1;
dfs(i + 1);
col[j] = dg[i + j] = udg[n - i + j] = 0;
t[i][j] = '.';
}
}
};
dfs(0);
return ans;
}
};