-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathNQUEEN.C
122 lines (97 loc) · 1.49 KB
/
NQUEEN.C
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
/* N-QUEEN PROBLEM */
#include<stdio.h>
#include<conio.h>
static int count=0;
int x[100];
int mat[100][100]={0};
void nqueen(int k, int n);
int place(int k, int i);
void init(int n);
void show(int n);
int main()
{
int n;
clrscr();
printf("Enter the value of n: ");
scanf("%d",&n);
printf("\nThe solutions are: \n");
nqueen(1,n);
printf("\nThe total number of solutions is %d",count);
getch();
return 0;
}
void nqueen(int k,int n)
{
int i,j;
for(i=1;i<=n;i++)
{
if(place(k,i))
{
x[k]=i;
if(k==n)
{
for(j=1;j<=n;j++)
{
printf("%d ",x[j]);
}
count++;
printf("\n\nIn Matrix Form:\n");
show(n);
printf("\n");
init(n);
}
else
nqueen(k+1,n);
}
}
}
//Returns 1 if a queen can be placed in kth row and ith column
//Else returns 0
int place(int k,int i)
{
int j;
for(j=1;j<k;j++)
if((x[j]==i) || (abs(x[j]-i)==abs(j-k)))
return 0;
return 1;
}
void show(int n)
{
int i, j;
for(i=1;i<=n;i++)
{
mat[i][x[i]]=1;
}
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
printf("%d ", mat[i][j]);
}
printf("\n");
}
}
void init(int n)
{
int i,j;
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
mat[i][j]=0;
}
/* OUTPUT
Enter the value of n: 4
The solutions are:
2 4 1 3
In Matrix Form:
0 1 0 0
0 0 0 1
1 0 0 0
0 0 1 0
3 1 4 2
In Matrix Form:
0 0 1 0
1 0 0 0
0 0 0 1
0 1 0 0
The total number of solutions is 2
*/