Skip to content

Commit e21aae5

Browse files
authored
Merge pull request #683 from harshita9621/master
N-Queen Problem using C++
2 parents ba9d41e + 48db6d3 commit e21aae5

File tree

1 file changed

+108
-0
lines changed

1 file changed

+108
-0
lines changed

Backtracking/N-Queen Problem.cpp

Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
/* N-Queen Problem
2+
3+
4+
You have to place n queens on an nxn chessboard.
5+
Idea: Try all the possible positions for the queen. isSafe functions check whether
6+
the current position is safe or not
7+
8+
*/
9+
10+
#include<iostream>
11+
using namespace std;
12+
13+
14+
bool isSafe(int board[][10], int i, int j, int n){
15+
//Check in col
16+
17+
for(int row=0;row<i;row++){
18+
if(board[row][j] == 1){
19+
return false;
20+
}
21+
}
22+
//Left diagonal
23+
int x=i;
24+
int y=j;
25+
26+
while(x>=0 && y>=0){
27+
if(board[x][y]==1){
28+
return false;
29+
}
30+
x--;
31+
y--;
32+
}
33+
//Right diagonal
34+
x=i;
35+
y=j;
36+
37+
while(x>=0 && y>=0){
38+
if(board[x][y]==1){
39+
return false;
40+
}
41+
x--;
42+
y++;
43+
}
44+
//The position is safe
45+
return true;
46+
47+
48+
}
49+
50+
bool nQueen(int board[][10], int i,int n){
51+
if(i==n){//base case
52+
// Place Queeen in n rows (0..n-1)
53+
//print the board
54+
for(int i=0;i<n;i++){
55+
for(int j=0;j<n;j++){
56+
if(board[i][j]==1){
57+
cout<<"Q ";
58+
}
59+
else{
60+
cout<<"_ ";
61+
}
62+
}
63+
cout<<endl;
64+
}
65+
return true;
66+
}
67+
//Recursive case
68+
69+
for(int j=0;j<n;j++){
70+
//Check i,j th position is safe to place the queen or not.
71+
if(isSafe(board,i,j,n)){
72+
//Place the Queen ,i, j in the right position
73+
board[i][j]=1;
74+
75+
if(nQueen(board,i+1,n)){
76+
return true;
77+
}
78+
//Means i,j is not the right position
79+
board[i][j]=0; //backtracking
80+
}
81+
}
82+
//coudln't place the queen in current position.
83+
return false;
84+
}
85+
86+
87+
int main(){
88+
int n;
89+
cin>>n;
90+
91+
int board[10][10]={0};
92+
nQueen(board,0,n);
93+
94+
return 0;
95+
96+
}
97+
98+
/* Input:
99+
4
100+
101+
Output:
102+
103+
_ Q _ _
104+
_ _ _ Q
105+
Q _ _ _
106+
_ _ Q _
107+
108+
*/

0 commit comments

Comments
 (0)