-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path052_N-Queens_II.cpp
43 lines (41 loc) · 1.12 KB
/
052_N-Queens_II.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
class Solution {
private:
bool checkValid(vector<string> &in, int i, int j) {
for (int idx = 0; idx < i; idx ++) {
if (in[idx][j] == 'Q') {
return false;
}
if (in[idx][j + i - idx] == 'Q' and j + i - idx >= 0 and j + i - idx <= in.size() - 1) {
return false;
}
if (in[idx][j - i + idx] == 'Q' and j - i + idx >= 0 and j - i + idx <= in.size() - 1) {
return false;
}
}
return true;
}
void solve(vector<string> &in, int &out, int n) {
if (n >= in.size()) {
out ++;
return;
}
for (int i = 0; i < in.size(); i ++) {
if (checkValid(in, n, i)) {
in[n][i] = 'Q';
solve(in, out, n + 1);
in[n][i] = '.';
}
}
}
public:
int totalNQueens(int n) {
int ans = 0;
vector<string> in;
for (int i = 0; i < n; i ++) {
string temp(n, '.');
in.emplace_back(temp);
}
solve(in, ans, 0);
return ans;
}
};