forked from TARANG0503/DSA-Practice
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathN-Queens_II.cpp
47 lines (41 loc) · 1.19 KB
/
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
class Solution {
public:
bool isPres(int row, int col, int xMv, int yMv, int& n, vector<vector<bool>>& isTkn){
while((row>=0)&&(row<n)&&(col>=0)&&(col<n)){
if(isTkn[row][col]){
return true;
}
row+=xMv;
col+=yMv;
}
return false;
}
int recFn(int row, int& n, vector<vector<bool>>& isTkn){
if(row==n){
return 1;
}
int res=0;
for(int col=0; col<n; col++){
// Checking top.
if(isPres(row, col, -1, 0, n, isTkn)){
continue;
}
// Checking top-left.
if(isPres(row, col, -1, -1, n, isTkn)){
continue;
}
// Checking top-right.
if(isPres(row, col, -1, 1, n, isTkn)){
continue;
}
isTkn[row][col]=true;
res+=recFn(row+1, n, isTkn);
isTkn[row][col]=false;
}
return res;
}
int totalNQueens(int n) {
vector<vector<bool>> isTkn(n, vector<bool>(n, false));
return recFn(0, n, isTkn);
}
};