题目描述
n 皇后问题研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击。
上图为 8 皇后问题的一种解法。
给定一个整数 n,返回 n 皇后不同的解决方案的数量。
示例:
输入: 4
输出: 2
解释: 4 皇后问题存在如下两个不同的解法。
[
[".Q…", // 解法 1
“…Q”,
“Q…”,
“…Q.”],
["…Q.", // 解法 2
“Q…”,
“…Q”,
“.Q…”]
]
分析
主要是和第51题一样,仍然是使用递归深度搜索与回溯。易错的点就是如何判断任意两个皇后是否在同一个对角线以及是否在用一条斜对角线。
代码
class Solution {
public:
int ans = 0;
vector<vector<char> > res;
//是否在同一行,是不用判断的,按照递归的过程,肯定不会在相同行
//判断是不是在同一列
bool isSameColumn(int depth, int c1){
//遍历res的所有行的当前的列是否已经放置了元素
for(int i=0;i<depth;i++){
if(res[i][c1]=='Q') return true;
}
return false;
}
//判断是不是在同一个对角线
bool isSamediagonal(int depth, int c1){
for(int i=1;i<=depth;i++){
if((c1-i)>=0 && res[depth-i][c1-i]=='Q') return true;
}
return false;
}
//判断是不是在同一个斜对角线
bool isSamediagonal2(int depth, int c1){
for(int i=1;i<=depth;i++){
if((c1+i)<res.size() && res[depth-i][c1+i]=='Q') return true;
}
return false;
}
//递归函数,主要是选择多个不同的列, 这个深度表示的是第几行
void dfs(int n, int depth){
//递归出口
if(depth==n){
ans += 1;
}
for(int i=0;i<n;i++){//当前行的列号
if(!isSameColumn(depth, i) && !isSamediagonal(depth, i) && !isSamediagonal2(depth, i)){
res[depth][i] = 'Q';
dfs(n, depth+1);
res[depth][i] = '.';//回溯
}
}
}
int totalNQueens(int n) {
//题目返回的是n皇后摆法的数量
//n皇后要求不能在同一行, 不能在同一列,不能在同一对角线(包括正对角线和斜对角线)
res.resize(n, vector<char>(n, '.'));
dfs(n, 0);
return ans;
}
};