-
Notifications
You must be signed in to change notification settings - Fork 0
/
n_queen.cpp
96 lines (73 loc) · 1.88 KB
/
n_queen.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
88
89
90
91
92
93
94
95
96
#include<iostream>
using namespace std;
bool canPlace(char board[][100],int row,int col,int n){
// searching for valid space row wise
for(int i=0;i<n;i++){
if(board[row][i]=='Q'){
return false;
}
}
// searching for valid space column wise
for(int i=0;i<n;i++){
if(board[i][col]=='Q'){
return false;
}
}
// searching for diagnols places
// from top left
int i=row,j=col;
while(i>=0&&j>=0){
if(board[i][j]=='Q'){
return false;
}
i--;
j--;
}
// from top right
i=row,j=col;
while(i>=0 && j<n){
if(board[i][j]=='Q'){
return false;
}
i--;
j++;
}
return true;
}
bool solveNQueen(char board[][100],int n,int row){
if(row==n){
// Print the board
for(int x=0;x<n;x++){
for(int y=0;y<n;y++){
cout<<board[x][y]<<" ";
}
cout<<endl;
}
return true;
}
// Try to place the queen in the current row
for(int pos=0;pos<n;pos++){
if(canPlace(board,row,pos,n)){
board[row][pos]='Q';
bool agliQueenRakhPayeKya = solveNQueen(board,n,row+1);
if(agliQueenRakhPayeKya==true){
return true;
}
board[row][pos]='.';
}
}
///Backtracking
return false;
}
int main(){
char board[100][100];
int n;
cin>>n;
for(int x=0;x<n;x++){
for(int y=0;y<n;y++){
board[x][y]='.';
}
}
solveNQueen(board,n,0);
return 0;
}