-
Notifications
You must be signed in to change notification settings - Fork 1
/
038_05-N皇后.cpp
53 lines (46 loc) · 1.23 KB
/
038_05-N皇后.cpp
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
class Solution {
public:
vector<vector<string>> solveNQueens(int n) {
if(n<=0)
return res;
vector<int> nums;
nums.resize(n);
for(int i=0;i<n;i++)
nums[i]=i;
solveNQueensCore(nums,0);
return res;
}
void solveNQueensCore(vector<int> &nums, int begin){
if(begin==nums.size()){
if(check(nums))
draw(nums);
return;
}
for(int i=begin;i<nums.size();i++){
swap(nums[begin],nums[i]);
solveNQueensCore(nums,begin+1);
swap(nums[begin],nums[i]);
}
}
bool check(vector<int>& nums){
for(int i=0;i<nums.size();i++){
for(int j=0;j<nums.size();j++){
if(i==j)
continue;
if(fabs(nums[i]-nums[j])==j-i){
return false;
}
}
}
return true;
}
void draw(vector<int>& nums){
string temp(nums.size(),'.');
vector<string> v(nums.size(),temp);
for(int i=0;i<nums.size();i++){
v[nums[i]][i]='Q';
}
res.push_back(v);
}
vector<vector<string>> res;
};