-
Notifications
You must be signed in to change notification settings - Fork 0
/
Q52.cpp
49 lines (38 loc) · 1.02 KB
/
Q52.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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include<vector>
#include<string>
using namespace std;
class Solution {
public:
void recurse(vector<string> solution, int pos, vector<vector<bool>> validPos, int& result){
int n = solution[0].size();
if (pos == n){
result++; return;
}
for (int i = 0; i < n; i++){
if (!validPos[pos][i]) continue;
vector<vector<bool>> newPos = validPos;
for (int j = pos; j < n; j++){
newPos[j][i] = false;
if (i - j + pos >= 0) newPos[j][i - j + pos] = false;
if (i + j - pos < n) newPos[j][i + j - pos] = false;
}
solution[pos][i] = 'Q';
recurse(solution, pos + 1, newPos, result);
solution[pos][i] = '.';
}
return;
}
int totalNQueens(int n) {
int result = 0;
vector<string> solution(n, string(n, '.'));
vector<vector<bool>> validPos = vector<vector<bool>>(n, vector<bool>(n, true));
recurse(solution, 0, validPos, result);
return result;
}
};
int main(void){
int n = 5;
Solution model;
int result = model.totalNQueens(n);
return 0;
}