-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path52.n-queens-ii.cpp
More file actions
37 lines (32 loc) · 869 Bytes
/
52.n-queens-ii.cpp
File metadata and controls
37 lines (32 loc) · 869 Bytes
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 {
public:
int totalNQueens(int n) {
vector<int> qplace(n, -1);
int res = 0;
solve(qplace, 0, res);
return res;
}
bool solve(vector<int>& qplace, int row, int& res){
int len = qplace.size();
if(row == len){
res++;
return false;
}
for(int i=0; i<len; i++){
if(check(qplace, row, i)){
qplace[row] = i;
if(solve(qplace, row+1, res))
return true;
}
}
qplace[row] = -1;
return false;
}
bool check(vector<int>& qplace, int row, int col){
for(int k=0; k<qplace.size(); k++){
if(col == qplace[k] || (row-k) == abs(col-qplace[k]))
return false;
}
return true;
}
};