-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path51.cpp
More file actions
43 lines (41 loc) · 1.48 KB
/
Copy path51.cpp
File metadata and controls
43 lines (41 loc) · 1.48 KB
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
class Solution {
public:
vector<vector<string>> solveNQueens(int n) {
vector<vector<string>> res;
string temp = "";
for (int i = 0; i < n; ++i)
temp += ".";
vector<string> board(n, temp);
unordered_map<int, bool> left_diagonal, right_diagonal;
vector<bool> row(n, false), col(n, false);
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
left_diagonal[i + j] = false;
right_diagonal[i - j] = false;
}
}
Backtrack(0, n, board, res, col, left_diagonal, right_diagonal);
return res;
}
void Backtrack(int i, int &n, vector<string> &board, vector<vector<string>> &res,
vector<bool> &col, unordered_map<int, bool> &left_diagonal,
unordered_map<int, bool> &right_diagonal) {
if (i == n) {
res.push_back(board);
return;
}
for (int j = 0; j < n; ++j) {
if (!col[j] && !left_diagonal[i + j] && !right_diagonal[i - j]) {
col[j] = true;
left_diagonal[i + j] = true;
right_diagonal[i - j] = true;
board[i][j] = 'Q';
Backtrack(i + 1, n, board, res, col, left_diagonal, right_diagonal);
board[i][j] = '.';
col[j] = false;
left_diagonal[i + j] = false;
right_diagonal[i - j] = false;
}
}
}
};