题意
求N皇后问题的解
思路
回溯法,最后递归返回时还原路径即可。
代码
class Solution {
private:
int a[100];
int n;
vector<vector<string>> ans;
public:
void dfs(int step) {
if (step >= n) {
vector<string> tmp;
for (int i = 0; i < n; i++) {
string s = "";
for (int j = 0; j < n; j++) {
if (a[i] == j) s.push_back('Q');
else s.push_back('.');
}
tmp.push_back(s);
}
ans.push_back(tmp);
return;
}
for (int i = 0; i < n; i++) {
bool ok = true;
for (int j = 0; j < step; j++) {
if (a[j] == i || (abs(a[j] - i) == abs(j - step))) {ok = false; break;}
}
if (ok) {
a[step] = i;
dfs(step + 1);
a[step] = -1;
}
}
}
vector<vector<string>> solveNQueens(int n) {
memset(a, -1, sizeof(a));
this->n = n;
dfs(0);
return ans;
}
};