-
Notifications
You must be signed in to change notification settings - Fork 0
/
N_QueensII.cpp
46 lines (41 loc) · 1.07 KB
/
N_QueensII.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
/*
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) {
this->count = 0;
this->columns = vector<int>(n,0);
this->main_diag = vector<int>(2*n,0);
this->anti_diag = vector<int>(2*n,0);
vector<int> C(n,0);
dfs(C,0);
return this->count;
}
private:
private:
int count;
vector<int> columns;
vector<int> main_diag;
vector<int> anti_diag;
void dfs(vector<int> &C,int row)
{
const int N = C.size();
if(row == N)
{
++this->count;
return;
}
for(int j = 0;j<N;++j)
{
const bool flag = columns[j] == 0&&main_diag[row+j] == 0&&anti_diag[row-j+N] == 0;
if(!flag)
continue;
C[row] = j;
columns[j] = main_diag[row+j]=anti_diag[row-j+N] = 1;
dfs(C,row+1);
columns[j] = main_diag[row+j] = anti_diag[row-j+N] = 0;
}
}
};