-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0052-n-queens-ii.cpp
More file actions
50 lines (49 loc) · 1.32 KB
/
0052-n-queens-ii.cpp
File metadata and controls
50 lines (49 loc) · 1.32 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
#include<string>
#include<vector>
using namespace std;
class Solution {
public:
int _n, ans;
vector<vector<bool>> curr;
vector<bool> col;
int dirs[4][2] = {{-1, -1}, {-1, 1}};
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)
ans++;
else
recur(row + 1);
curr[row][i] = false;
col[i] = false;
}
}
}
int totalNQueens(int n) {
_n = n;
ans = 0;
curr.resize(n, vector<bool>(n, false));
col.resize(n, false);
recur(0);
return ans;
}
};