代码
class Solution {
public:
int N;
vector<bool> col, dg, udg;
vector<vector<string>> ans;
vector<string> path;
vector<vector<string>> solveNQueens(int n) {
N = n;
col = vector<bool>(N);
dg = udg = vector<bool>(N * 2);
path = vector<string>(N, string(n, '.'));
dfs(0);
return ans;
}
void dfs(int u) {
if (u == N) {
ans.push_back(path);
return ;
}
for (int i = 0; i < N; ++i) {
if (!col[i] && !dg[u - i + N] && !udg[u + i]) {
col[i] = dg[u - i + N] = udg[u + i] = true;
path[u][i] = 'Q';
dfs(u + 1);
path[u][i] = '.';
col[i] = dg[u - i + N] = udg[u + i] = false;
}
}
}
};