-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0051. N-Queens.cpp
51 lines (44 loc) · 1.27 KB
/
0051. N-Queens.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
class Solution
{
unordered_set<int> columns;
unordered_set<int> diagonals_1;
unordered_set<int> diagonals_2;
int n;
vector<vector<string>> ans;
vector<string> board;
public:
vector<vector<string>> solveNQueens(int n)
{
this->n = n;
board = vector<string>(n, string(n, '.'));
dfs(0);
return ans;
}
void dfs(int row)
{
if (row == n)
{
ans.push_back(board);
}
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())
{
board[row][col] = 'Q';
columns.insert(col);
diagonals_1.insert(row - col);
diagonals_2.insert(col + row);
dfs(row + 1);
board[row][col] = '.';
columns.erase(col);
diagonals_1.erase(row - col);
diagonals_2.erase(col + row);
}
}
}
}
};