-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path0051.cpp
More file actions
46 lines (40 loc) · 1.16 KB
/
Copy path0051.cpp
File metadata and controls
46 lines (40 loc) · 1.16 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
44
45
46
class Solution {
vector<vector<string>> res;
vector<string> board;
unordered_set<int> used;
int n;
bool valid(int row, int col) { return row >= 0 && row < n && col >= 0 && col < n; }
bool safe(int row, int col) {
static vector<pair<int, int>> ofsts = {{1, 1}, {1, -1}, {-1, 1}, {-1, -1}};
if (used.count(col)) return false;
for (auto &ofst : ofsts) {
int a = row + ofst.first, b = col + ofst.second;
while (valid(a, b)) {
if (board[a][b] == 'Q') return false;
a += ofst.first, b += ofst.second;
}
}
return true;
}
void rec(int row) {
if (row == n) {
res.push_back(board);
return;
}
for (int i = 0; i < n; i++) {
if (!safe(row, i)) continue;
used.insert(i);
board[row][i] = 'Q';
rec(row + 1);
used.erase(i);
board[row][i] = '.';
}
}
public:
vector<vector<string>> solveNQueens(int n) {
this->n = n;
board = vector<string>(n, string(n, '.'));
rec(0);
return res;
}
};