按照全排列的搜索顺序dfs 另一种搜索顺序 见基础班模板 题解 全排列搜索顺序(n皇后) 和更加原始搜索顺序
class Solution {
public:
int n;
vector<vector<string>> ans;
vector<string> path;
vector<bool> col, dg, udg;
vector<vector<string>> solveNQueens(int _n) {
n = _n;
col = vector<bool>(n);
dg = udg = vector<bool>(2 * n);
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;
}
}
}
};