Skip to content

Commit 77761e3

Browse files
authored
Create n-queens.cpp
1 parent 693aada commit 77761e3

File tree

1 file changed

+90
-0
lines changed

1 file changed

+90
-0
lines changed

C++/n-queens.cpp

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
4+
int n;
5+
vector<vector<int>> board;
6+
vector<vector<vector<int>>> v;
7+
8+
/*
9+
Give input n = no. of queens...
10+
Output --> All Combinations of positions of n queens so that no queen can attack other..
11+
*/
12+
13+
bool is_safe(int row, int col){
14+
15+
int x = row, y = col;
16+
//check for same row
17+
while(y>=0){
18+
if(board[x][y]==1){return false;}
19+
y--;
20+
}
21+
22+
int xx = row, yy = col;
23+
//check for diagonal
24+
while(xx>=0 && yy>=0){
25+
if(board[xx][yy]==1){return false;}
26+
xx--; yy--;
27+
}
28+
29+
int a = row, b = col;
30+
//check for diagonal
31+
while(a<n && b>=0){
32+
if(board[a][b]==1){return false;}
33+
a++; b--;
34+
}
35+
36+
return true;
37+
38+
}
39+
40+
41+
42+
void solve(int col, int n){
43+
44+
// base case (if every col is filled)
45+
if(col == n){
46+
v.push_back(board);
47+
return;
48+
}
49+
50+
//put queen in every row of diff col..
51+
for(int row = 0; row<n; row++){
52+
if(is_safe(row,col)){
53+
54+
// if placing queen is safe
55+
board[row][col] = 1;
56+
57+
solve(col+1, n);
58+
59+
//backtrack
60+
board[row][col] = 0;
61+
}
62+
}
63+
64+
65+
}
66+
67+
int main()
68+
{
69+
cin>>n;
70+
71+
for(int i=0; i<n; i++){
72+
vector<int> temp(n, 0);
73+
board.push_back(temp);
74+
}
75+
76+
solve(0, n);
77+
cout<<v.size()<<"\n";
78+
79+
for(auto b : v){
80+
for(auto vv : b){
81+
for(int g : vv){
82+
cout<<g<<" ";
83+
}
84+
cout<<"\n";
85+
}
86+
cout<<"\n\n";
87+
}
88+
89+
90+
}

0 commit comments

Comments
 (0)