-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0051-n-queens.cpp
More file actions
58 lines (57 loc) · 1.58 KB
/
0051-n-queens.cpp
File metadata and controls
58 lines (57 loc) · 1.58 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
47
48
49
50
51
52
53
54
55
56
57
58
#include<string>
#include<vector>
using namespace std;
class Solution {
public:
int _n;
vector<vector<string>> ans;
vector<vector<bool>> curr;
vector<bool> col;
int dirs[4][2] = {{1, 1}, {-1, -1}, {1, -1}, {-1, 1}};
void saveAns() {
vector<string> vec(_n, "");
for (int i = 0; i < _n; i++) {
for (auto val : curr[i])
vec[i] += val ? "Q" : ".";
}
ans.push_back(vec);
}
void recur(int row) {
for (int i = 0; i < _n; i++) {
if (col[i])
continue;
bool isSafe = true;
for (int j = 1; j < _n; j++) {
for (auto dir : dirs) {
int nrow = row + j * dir[0];
int ncol = i + j * dir[1];
if (nrow < 0 || ncol < 0 || nrow >= _n || ncol >= _n)
continue;
if (curr[nrow][ncol]) {
isSafe = false;
break;
}
}
if (!isSafe)
break;
}
if (isSafe) {
curr[row][i] = true;
col[i] = true;
if (row == _n - 1)
saveAns();
else
recur(row + 1);
curr[row][i] = false;
col[i] = false;
}
}
}
vector<vector<string>> solveNQueens(int n) {
_n = n;
curr.resize(n, vector<bool>(n, false));
col.resize(n, false);
recur(0);
return ans;
}
};