Skip to content

Commit e948213

Browse files
committed
Added N-Queen in cpp
1 parent 3e37e31 commit e948213

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

Backtracking/N-Queen/C++/N-Queen.cpp

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
#include<iostream>
2+
3+
using namespace std;
4+
#define N 5
5+
6+
void printBoard(int board[N][N]){
7+
for(int i=0;i<N;i++){
8+
for(int j=0;j<N;j++)
9+
cout<<board[i][j]<<" ";
10+
cout<<endl;
11+
}
12+
}
13+
14+
bool isValid(int board[N][N], int row, int col){
15+
for(int i=0;i<col;i++)
16+
if(board[row][i])
17+
return false;
18+
19+
for(int i=row,j=col;i>=0 && j>=0;i--,j--)
20+
if(board[i][j])
21+
return false;
22+
23+
for(int i=row,j=col;j>=0 && i<N;i++,j--)
24+
if(board[i][j])
25+
return false;
26+
27+
return true;
28+
}
29+
30+
bool solveNQueen(int board[N][N], int col){
31+
if(col>=N)
32+
return true;
33+
34+
for(int i=0;i<N;i++){
35+
if(isValid(board, i, col)){
36+
board[i][col] = 1;
37+
if(solveNQueen(board,col+1))
38+
return true;
39+
40+
board[i][col] = 0;
41+
}
42+
}
43+
return false;
44+
}
45+
46+
bool checkSolution(){
47+
int board[N][N];
48+
for(int i=0;i<N;i++)
49+
for(int j=0;j<N;j++)
50+
board[i][j] = 0;
51+
52+
if(!solveNQueen(board,0)){
53+
cout<<"Solution does not exist"<<endl;
54+
return false;
55+
}
56+
57+
printBoard(board);
58+
return true;
59+
}
60+
61+
int main(){
62+
checkSolution();
63+
}

0 commit comments

Comments
 (0)