Skip to content

Commit 8d774bd

Browse files
committed
cpp
1 parent f5020fc commit 8d774bd

File tree

1 file changed

+87
-0
lines changed

1 file changed

+87
-0
lines changed

51.cpp

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
class Solution {
2+
public:
3+
bool issafe(vector<vector<int>>&board,int i,int j,int n){
4+
//top wala
5+
for(int top=0;top<i;top++){
6+
if(board[top][j]==1){
7+
return 0;
8+
}
9+
}
10+
11+
//left daigonal
12+
13+
int x=i;
14+
int y=j;
15+
16+
while(x>=0 && y>=0){
17+
if(board[x][y]==1){
18+
return 0;
19+
}
20+
x--;
21+
y--;
22+
}
23+
24+
// right daigonal
25+
26+
x=i;
27+
y=j;
28+
29+
while(x>=0 && y<n){
30+
if(board[x][y]==1){
31+
return 0;
32+
}
33+
x--;
34+
y++;
35+
}
36+
return 1;
37+
}
38+
39+
bool solve(vector<vector<int>>& board ,int n,int i,vector<vector<string>>&ans){
40+
if(i==n){
41+
vector<vector<string>> vec( n , vector<string> (n, "."));
42+
for(int i=0;i<n;i++){
43+
for(int j=0;j<n;j++){
44+
if(board[i][j]==1){
45+
vec[i][j]='Q';
46+
}
47+
else{
48+
vec[i][j]='.';
49+
}
50+
}
51+
}
52+
vector<string>temp;
53+
for(int i=0;i<n;i++){
54+
string ss="";
55+
for(int j=0;j<n;j++){
56+
ss+=vec[i][j];
57+
}
58+
temp.push_back(ss);
59+
}
60+
ans.push_back(temp);
61+
return 0;
62+
}
63+
for(int k=0;k<n;k++){
64+
if(issafe(board,i,k,n)){
65+
board[i][k]=1;
66+
if(solve(board,n,i+1,ans)){
67+
return 1;
68+
}
69+
board[i][k]=0;
70+
}
71+
}
72+
return 0;
73+
}
74+
75+
vector<vector<string>> solveNQueens(int n) {
76+
77+
78+
vector<vector<int>> board( n , vector<int> (n, 0));
79+
80+
vector<vector<string>>ans;
81+
82+
solve(board,n,0,ans);
83+
84+
return ans;
85+
86+
}
87+
};

0 commit comments

Comments
 (0)