-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0052. N-Queens II.cpp
46 lines (40 loc) · 1.05 KB
/
0052. 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
class Solution
{
unordered_set<int> columns;
unordered_set<int> diagonals_1;
unordered_set<int> diagonals_2;
int n;
int ans;
public:
int totalNQueens(int n)
{
this->n = n;
dfs(0);
return ans;
}
void dfs(int row)
{
if (row == n)
{
++ans;
}
else
{
for (int col = 0; col < n; ++col)
{
if (columns.find(col) == columns.end()
and diagonals_1.find(row - col) == diagonals_1.end()
and diagonals_2.find(col + row) == diagonals_2.end())
{
columns.insert(col);
diagonals_1.insert(row - col);
diagonals_2.insert(col + row);
dfs(row + 1);
columns.erase(col);
diagonals_1.erase(row - col);
diagonals_2.erase(col + row);
}
}
}
}
};