LeetCode-52-N皇后II

n 皇后问题研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击。

上图为 8 皇后问题的一种解法。

给定一个整数 n,返回 n 皇后不同的解决方案的数量。

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
输入: 4
输出: 2
解释: 4 皇后问题存在如下两个不同的解法。
[
[".Q..", // 解法 1
"...Q",
"Q...",
"..Q."],

["..Q.", // 解法 2
"Q...",
"...Q",
".Q.."]
]

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class Solution {
//时间复杂度:O(n^2)
//空间复杂度:O(N) 标记数组
public:
int totalNQueens(int n) {
//标记数组,索引表示行,值表示列
vector<int> nums(n,-1);
int count=0;
DFS(0,n,nums,count);
return count;
}

void DFS(int deepth,int n,vector<int>& nums,int& count){
if(deepth==n){
count++;
return;
}

//检测第i列是否合法
for(int i=0;i<n;i++){
if(valid(deepth,i,nums)){
nums[deepth]=i;
DFS(deepth+1,n,nums,count);
nums[deepth]=-1;
}
}
}

bool valid(int row,int col,vector<int>& nums){
for(int i=0;i<nums.size();i++)
//判断是否同列或在对角线
if(col==nums[i]||(nums[i]>=0&&abs(row-i)==abs(col-nums[i])))
return false;

return true;
}
};

----\(˙<>˙)/----赞赏一下吧~