-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtotalNQueens.cpp
More file actions
31 lines (31 loc) · 825 Bytes
/
totalNQueens.cpp
File metadata and controls
31 lines (31 loc) · 825 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
class Solution {
public:
int totalNQueens(int n) {
int res = 0;
vector<int> pos(n, -1);
totalNQueens(pos, 0, res);
return res;
}
private:
void totalNQueens(vector<int> &pos, int row, int &res) {
int n = pos.size();
if (row == n) ++res;
else {
for (int col = 0; col < n; ++col) {
if (isValid(pos, row, col)) {
pos[row] = col;
totalNQueens(pos, row + 1, res);
pos[row] = -1;
}
}
}
}
bool isValid(vector<int> &pos, int row, int col) {
for (int i = 0; i < row; ++i) {
if (col == pos[i] || abs(row - i) == abs(col - pos[i])) {
return false;
}
}
return true;
}
};