-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path51.cpp
87 lines (73 loc) · 1.96 KB
/
51.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
class Solution {
public:
bool issafe(vector<vector<int>>&board,int i,int j,int n){
//top wala
for(int top=0;top<i;top++){
if(board[top][j]==1){
return 0;
}
}
//left daigonal
int x=i;
int y=j;
while(x>=0 && y>=0){
if(board[x][y]==1){
return 0;
}
x--;
y--;
}
// right daigonal
x=i;
y=j;
while(x>=0 && y<n){
if(board[x][y]==1){
return 0;
}
x--;
y++;
}
return 1;
}
bool solve(vector<vector<int>>& board ,int n,int i,vector<vector<string>>&ans){
if(i==n){
vector<vector<string>> vec( n , vector<string> (n, "."));
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(board[i][j]==1){
vec[i][j]='Q';
}
else{
vec[i][j]='.';
}
}
}
vector<string>temp;
for(int i=0;i<n;i++){
string ss="";
for(int j=0;j<n;j++){
ss+=vec[i][j];
}
temp.push_back(ss);
}
ans.push_back(temp);
return 0;
}
for(int k=0;k<n;k++){
if(issafe(board,i,k,n)){
board[i][k]=1;
if(solve(board,n,i+1,ans)){
return 1;
}
board[i][k]=0;
}
}
return 0;
}
vector<vector<string>> solveNQueens(int n) {
vector<vector<int>> board( n , vector<int> (n, 0));
vector<vector<string>>ans;
solve(board,n,0,ans);
return ans;
}
};