-
Notifications
You must be signed in to change notification settings - Fork 1
/
0052.cpp
56 lines (44 loc) · 1.31 KB
/
0052.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
class Solution {
public:
int totalNQueens(int n) {
// see problem 51, even simpler
vector<int> order;
for (int i = 0; i < n; i++)
order.push_back(i);
int result = 0;
do
{
int blockLeft = 0;
int blockRight = 0;
bool ok = true;
int line;
for (line = 0; line < order.size(); line++)
{
int pos = order[line];
int mask = 1 << pos;
ok &= (mask & blockLeft) == 0;
ok &= (mask & blockRight) == 0;
blockLeft <<= 1;
blockRight >>= 1;
blockRight &= (1 << n) - 1;
if (!ok)
break;
blockLeft |= mask << 1;
blockRight |= mask >> 1;
}
if (ok)
result++;
else
{
// skip permutations
if (line < n - 1)
{
// not perfect, but fast
sort (order.begin() + line + 1, order.end());
reverse(order.begin() + line + 1, order.end());
}
}
} while (next_permutation(order.begin(), order.end()));
return result;
}
};