-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy path52. N-Queens II.cpp
31 lines (31 loc) · 966 Bytes
/
52. N-Queens II.cpp
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
/*N-Queens II:Follow up for N-Queens problem. Now, instead outputting board configurations, return the total number of distinct solutions.*/
class Solution {
public:
int totalNQueens(int n) {
int res = 0;
vector<int> pos(n, -1);
totalNQueensDFS(pos, 0, res);
return res;
}
void totalNQueensDFS(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;
totalNQueensDFS(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;
}
};