51. N 皇后
题目链接
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/n-queens/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题目描述
题目分析
画树,树的高度=n
class Solution {
private:
vector<vector<string>> res;
void backtracking(int n, int row, vector<string>& path){
if(row == n){
res.push_back(path);
return ;
}
for(int col = 0; col < n; col++){
if(isVaild(row, col, path, n)){
path[row][col] = 'Q';
backtracking(n, row + 1, path);
path[row][col] = '.';
}
}
}
bool isVaild(int row, int col, vector<string>& path, int n){
for(int i = 0; i < row; i++){
if(path[i][col] == 'Q'){//如果col列有Q
return false;
}
}
for(int i = row - 1, j = col - 1; i >=0 && j >= 0; i--, j--){//注意是i >=0 && j >= 0 不是row col
if(path[i][j] == 'Q'){//检查右斜列
return false;
}
}
for(int i = row - 1, j = col + 1; i >=0 && j <= n; i--, j++){//注意j = col + 1
if(path[i][j] == 'Q'){//检查左斜列
return false;
}
}
return true;
}
public:
vector<vector<string>> solveNQueens(int n) {
res.clear();
std::vector<std::string> path(n, std::string(n, '.'));
backtracking(n, 0, path);
return res;
}
};