-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnqueens.cpp
More file actions
70 lines (65 loc) · 1007 Bytes
/
nqueens.cpp
File metadata and controls
70 lines (65 loc) · 1007 Bytes
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
#include<stdio.h>
#include<stdlib.h>
#define N 8
int board[N][N];
int n;
void printresult(){
int i,j;
for(i=0;i<n;i++){
for(j=0;j<n;j++){
printf("%d ",board[i][j]);
}
printf("\n");
}
}
bool issafe(int row2,int col2){
int i,j;
for(j=0;j<col2;j++){
for(i=0;i<n;i++){
if(board[i][j] == 1){
if(i == row2 || j == col2){
return false;
}
if(abs(i-row2) == abs(j-col2)){
return false;
}
}
}
}
return true;
}
bool nqueen(int col){
int i,j;
if(col>=n){
return true;
}
for(i=0;i<n;i++){
if(issafe(i,col)){
board[i][col] = 1;
if(nqueen(col+1)){
return true;
}
board[i][col] = 0;
}
}
return false;
}
int main(){
int i,j;
bool result;
printf("Enter no of queens:");
scanf("%d",&n);
for(i=0;i<n;i++){
for(j=0;j<n;j++){
board[i][j] = 0;
}
}
result = nqueen(0);
if(result){
printresult();
}
else{
printf("Solution does not exist");
}
return 0;
}