forked from larissalages/code_problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path51.cpp
More file actions
52 lines (47 loc) · 952 Bytes
/
51.cpp
File metadata and controls
52 lines (47 loc) · 952 Bytes
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
#define f first
#define s second
class Solution {
private:
int n;
vector<string> board;
vector<vector<string>> res;
void solve(int row) {
if (row == n) {
res.push_back(board);
return;
}
for (int col = 0; col < n; ++col)
{
board[row][col] = 'Q';
if (valid(row, col)) {
solve(row+1);
}
board[row][col] = '.';
}
}
bool valid(int ROW, int COL) {
vector<pair<int,int>> dirs =
{{-1,-1}, {-1,0}, {-1,1},
{0, -1}, {0,1},
{1, -1}, {1, 0}, {1,1}};
for (auto d: dirs) {
int k = 1;
int nr = ROW + k*d.f, nc = COL + k*d.s;
while (nr < n && nc < n && nr >= 0 && nc >= 0) {
if (board[nr][nc] == 'Q')
return false;
k++;
nr = ROW + k*d.f;
nc = COL + k*d.s;
}
}
return true;
}
public:
vector<vector<string>> solveNQueens(int n) {
this->n = n;
this->board = vector<string> (n, string (n, '.'));
solve(0);
return res;
}
};