-
Notifications
You must be signed in to change notification settings - Fork 0
/
nqueen.cpp
65 lines (58 loc) · 1.42 KB
/
nqueen.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
#include<iostream>
using namespace std;
const int n = 5;
bool isok(int x,int y,int board[n][n]){
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if((i+j)==(x+y)){
if(board[i][j]!=0)
return false;
}
if((j-i) == (y-x)){
if(board[i][j]!=0)
return false;
}
if(board[x][j]!=0)
return false;
}
if(board[i][y]!=0)
return false;
}
//cout<<"\ntrue";
return true;
}
bool nqueen(int board[n][n],int nq){
if(nq==0){
return true;
}
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(isok(i,j,board)){
board[i][j]=1;
if(nqueen(board,nq-1)== true){
//cout<<"\napplied at yay"<<i<<":"<<j;
return true;
}
else{
//cout<<"\nnot applied at "<<i<<";"<<j;
board[i][j]=0;
}
}
}
}
return false;
}
int main(){
int board[n][n]={0};
if(nqueen(board,n)== false)
cout<<"\nnot possible.";
else{
cout<<"\n";
for(int i=0;i<n;i++){
for(int j=0;j<n;j++)
cout<<board[i][j]<<" ";
cout<<"\n";
}
}
return 0;
}