forked from sakshamchecker/Hacktoberfest-21
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNQueens.cpp
31 lines (31 loc) · 1.14 KB
/
NQueens.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
void solve(vector<vector<string>> &res, vector<string> &nQueens, int row, int &n){
if(row==n){
res.push_back(nQueens);
return;
}
for(int col=0; col!=n; col++){
if(isValid(nQueens,row,col,n)){
nQueens[row][col]='Q';
solve(res,nQueens,row+1,n);
nQueens[row][col]='.';
}
}
}
bool isValid(vector<string> &nQueens, int row, int col, int &n){
for(int i=0; i!=row; i++){
if(nQueens[i][col]=='Q')return false;
}
for(int i=row-1,j=col-1; i>=0 and j>=0; i--,j--){
if(nQueens[i][j]=='Q')return false;
}
for(int i=row-1, j=col+1; i>=0 and j<n; i--,j++){
if(nQueens[i][j]=='Q')return false;
}
return true;
}
vector<vector<string>> solveNQueens(int n) {
vector<vector<string>> res;
vector<string> nQueens(n,string(n,'.'));
solve(res,nQueens,0,n);
return res;
}