思路:
典型的DFS。时间复杂度O(N!),空间复杂度O(N)。
map[row]
表示第 i
row行的皇后放置的位置。
每一层有n种放置方法,一共有n层。
//N-Queens : dfs
class Solution {
private:
vector<vector<string>> res;
void addSolution(vector<int> &map, int n) {
vector<string> ans;
for(int i = 0; i < n; ++i) {
string row(n, '.');
row[map[i]] = 'Q';
ans.push_back(row);
}
res.push_back(ans);
}
bool canSet(vector<int> &map, int n, int row, int col) {
//if(map[row] != 0) //row
// return false;
int tmpcol = 0;
for(int tmprow = 0; tmprow < row; ++tmprow) {
tmpcol = map[tmprow];
if(tmpcol == col) //col
return false;
if((tmpcol - col) == (tmprow - row)) //right slant line
return false;
if((tmpcol - col) == (row - tmprow)) //left slant line
return false;
}
return true;
}
void nqueensSet(vector<int> &map, int n, int row) {
for(int i = 0; i < n; ++i) {
if(canSet(map, n, row, i)) {
map[row] = i;
if(row == n-1) {
addSolution(map, n);
map[row] = 0;
return;
}
nqueensSet(map, n, row+1);
map[row] = 0;
}
}
}
public:
vector<vector<string>> solveNQueens(int n) {
vector<int> map = vector<int>(n, 0);
//judge and set
nqueensSet(map, n, 0);
return res;
}
};