-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathN-Queens II.txt
39 lines (39 loc) · 1.01 KB
/
N-Queens II.txt
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
class Solution {
public:
int totalNQueens(int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int count = 0;
vector<int> pos;
for (int i = 0; i < n; i++)
pos.push_back(i);
plan(count, pos, 0);
return count;
}
void plan(int &count, vector<int>& pos, int p) {
if (p == pos.size())
count++;
else {
if (check(pos, p))
plan(count, pos, p+1);
for (int i = p + 1; i < pos.size(); i++) {
swap(pos[p], pos[i]);
if (check(pos, p))
plan(count, pos, p+1);
swap(pos[p], pos[i]);
}
}
}
bool check(vector<int> &pos, int p) {
for (int i = 0; i < p; i++) {
if (abs(i-p) == abs(pos[i] - pos[p]))
return false;
}
return true;
}
void swap(int& a, int& b) {
int t = a;
a = b;
b = t;
}
};