-
Notifications
You must be signed in to change notification settings - Fork 0
/
052. N-Queens II.cpp
74 lines (61 loc) · 2.25 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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
//Backtracking
//Runtime: 8 ms, faster than 52.40% of C++ online submissions for N-Queens II.
//Memory Usage: 6 MB, less than 84.99% of C++ online submissions for N-Queens II.
class Solution {
public:
int n;
void backtrack(vector<bool>& used_col, vector<bool>& used_pos_diag,
vector<bool>& used_neg_diag, int r, int& ans){
if(r == n){
++ans;
}else{
for(int c = 0; c < n; ++c){
if(!used_col[c] && !used_pos_diag[r-c+n-1] && !used_neg_diag[r+c]){
used_col[c] = true;
used_pos_diag[r-c+n-1] = true;
used_neg_diag[r+c] = true;
backtrack(used_col, used_pos_diag, used_neg_diag, r+1, ans);
used_col[c] = false;
used_pos_diag[r-c+n-1] = false;
used_neg_diag[r+c] = false;
}
}
}
};
int totalNQueens(int n) {
this->n = n;
int ans = 0;
vector<bool> used_col(n, false);
vector<bool> used_pos_diag(2*n-1, false);
vector<bool> used_neg_diag(2*n-1, false);
backtrack(used_col, used_pos_diag, used_neg_diag, 0, ans);
return ans;
}
};
//+speed up, vector<bool> -> vector<int>, build ans on the fly
//Runtime: 0 ms, faster than 100.00% of C++ online submissions for N-Queens II.
//Memory Usage: 6.2 MB, less than 56.45% of C++ online submissions for N-Queens II.
class Solution {
public:
int n;
void backtrack(vector<int>& used, int r, int& ans){
if(r == n){
++ans;
}else{
for(int c = 0; c < n; ++c){
if(!used[c] && !used[n+r-c+n-1] && !used[n+2*n-1+r+c]){
used[c] = used[n+r-c+n-1] = used[n+2*n-1+r+c] = true;
backtrack(used, r+1, ans);
used[c] = used[n+r-c+n-1] = used[n+2*n-1+r+c] = false;
}
}
}
};
int totalNQueens(int n) {
this->n = n;
int ans = 0;
vector<int> used(n + 2*n-1 + 2*n-1, false);
backtrack(used, 0, ans);
return ans;
}
};