-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.c
More file actions
164 lines (85 loc) · 2.42 KB
/
main.c
File metadata and controls
164 lines (85 loc) · 2.42 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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
#include<stdio.h>;
#include<math.h>;
int n = 0, col[20] = {0}, count = 0;
// column array and count getting initialized to zero
void solution()
{
int i, j;
for (i = 1; i <= n; i++)
/* loop for printing the solution vector which will show us the
placement of all the queens */
{
for (j = 1; j < col[i]; j++)
printf("x\t");
printf("q%d\t", i);
for (; j < n; j++)
printf("x\t");
printf("\n");
}
}
void nqueen(int q)
/* only row no. is needed to pass as a parameter to nqueen function
since queen no. is same as that of the row no. */
{
int c, i;
for (c = 1; c <= n; c++)
{
if (place(q, c)) // will call the place function
{
col[q] = c;
if (q == n)
// if all the queens are placed on the chessboard
{
count++;
printf("\n-- -- -- -- -- SOLUTION NUMBER : %d-- -- -- -- -- \n\n", count);
// suggests that multiple no. of solutions are possible
solution();
// call to solution function to display the result
}
else
/* else not placed then it will call the nqueen function and it will try to
place the next queen */
nqueen(q + 1); //function call
}
}
}
int place(int q, int c)
/* function will return true or false based on whether the queen is
placed or not ; q is the row no. and c is the column no. */
{
int k;
for (k = 1; k <= q - 1; k++)
{
if (c == col[k] || abs(k - q) == abs(col[k] - c))
// checks for (column attack or diagonal attack)
return 0;
}
return 1;
}
int main()
{
printf("ENTER THE NUMBER OF QUEENS:");
scanf("%d", &n);
// accepting no. of queens from the user
if (n < 3)
//solution cant be obtained for n<3
printf("\n NO SOLUTION FOR %d QUEEN PROBLEM\n", n);
else
nqueen(1); //call to nqueen function
}
/*
****************************************************
OUTPUT:
ENTER THE NUMBER OF QUEENS:4
-- -- -- -- -- -- -SOLUTION NUMBER : 1-- -- -- -- -- -- -- -- -- -- -- -- -- --
x q1 x x
x x x q2
q3 x x x
x x q4 x
-- -- -- -- -- -- -SOLUTION NUMBER : 2-- -- -- -- -- -- -- -- -- -- -- -- -- --
x x q1 x
q2 x x x
x x x q3
x q4 x x
****************************************************
*/