forked from imdhanish/HackerEarth
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNQueen.cpp
More file actions
104 lines (78 loc) · 1.73 KB
/
NQueen.cpp
File metadata and controls
104 lines (78 loc) · 1.73 KB
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
97
98
99
100
101
102
103
104
#include<iostream>
using namespace std;
bool canPlace(int board[][100],int row,int col,int n){
// Row mein queen to nahi h
for(int i=0;i<n;i++){
if(board[row][i]==1){
return false;
}
}
// Col mein queen to nahi h
for(int i=0;i<n;i++){
if(board[i][col]==1){
return false;
}
}
/// Diagonals
/// Top Left
int i=row,j=col;
while(i>=0&&j>=0){
if(board[i][j]==1){
return false;
}
i--;
j--;
}
///Top Right
i=row,j=col;
while(i>=0 && j<n){
if(board[i][j]==1){
return false;
}
i--;
j++;
}
return true;
}
bool solveNQueen(int 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;
}
///Rec Case
///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]=1;
bool agliQueenRakhPayeKya = solveNQueen(board,n,row+1);
if(agliQueenRakhPayeKya==true){
return true;
}
board[row][pos]=0;
}
}
///Backtracking
return false;
}
int main(){
int board[100][100];
int n;
cin>>n;
for(int x=0;x<n;x++){
for(int y=0;y<n;y++){
board[x][y]=0;
}
}
if(n < 4 && n > 1)
cout <<"Not possible" <<endl;
else{
solveNQueen(board,n,0);
}
return 0;
}