forked from iamAnki/CPP-Programs-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathn_queen.cpp
52 lines (48 loc) · 1.2 KB
/
n_queen.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
50
51
52
class Solution {
public:
vector<vector<string>> ans;
bool valid(vector<string> &v,int n,int row,int col)
{
for(int i =0; i<row; i++){
if(v[i][col]=='Q'){ // 90*
return false;
}
}
for(int i = row,j = col; i>=0 && j>=0; i--,j--){
if(v[i][j]=='Q'){ //45*
return false;
}
}
for(int i = row,j = col; i>=0 && j<n; i--,j++){
if(v[i][j]=='Q'){ //135*
return false;
}
}
return true;
}
void hlp(vector<string> &v,int r,int n)
{
if(r==v.size())
{
vector<string> chess = v;
ans.push_back(chess);
return;
}
for(int i=0;i<v.size();i++)
{
if(valid(v,v.size(),r,i))
{
v[r][i]='Q';
hlp(v,r+1,n);
v[r][i]='.';
}
}
return;
}
vector<vector<string>> solveNQueens(int n) {
string s(n,'.');
vector<string> b(n,s);
hlp(b,0,n);
return ans;
}
};