非常经典的问题,这里使用DFS解决,代码如下:
class Solution {
public:
vector<vector<string>> solveNQueens(int n) {
vector<vector<string>> res;
vector<string> nQueens(n,string(n,'.'));
solveNQueens(res,nQueens,0,n);
return res;
}
private:
void solveNQueens(vector<vector<string> > &res,vector<string> &nQueens, int row, int n) {
if(row == n){
res.push_back(nQueens);
return;
}
for(int col = 0;col < n;col++){
if(checksafe(nQueens,row,col,n)){
nQueens[row][col]='Q';
solveNQueens(res,nQueens,row + 1,n);
nQueens[row][col]='.';
}
}
}
bool checksafe(vector<string> &nQueens,int row,int col,int n){
//判断当前列是否有皇后
for(int i = 0;i < row;i++){
if(nQueens[i][col] == 'Q'){
return false;
}
}
//判断左上45度是否已有皇后
for(int i = row - 1,j = col - 1;i >= 0 && j >= 0;i--,j--){
if(nQueens[i][j] == 'Q'){
return false;
}
}
//判断右上45度是否已有皇后
for(int i = row - 1,j = col + 1;i >= 0 && j < n;i--,j++){
if(nQueens[i][j] == 'Q'){
return false;
}
}
return true;
}
};
运行结果:
Runtime: 8 ms, faster than 79.14% of C++ online submissions for N-Queens.
Memory Usage: 7.6 MB, less than 62.93% of C++ online submissions for N-Queens.