-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNqueens.c
66 lines (66 loc) · 1.16 KB
/
Nqueens.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
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int board[20],count;
void queen(int row,int n);
int main()
{
int n;
printf(" - N Queens Problem Using Backtracking -");
printf("\nEnter number of Queens:");
scanf("%d",&n);
if(n==2 ||n==3)
{
printf("No Solution\n");
return 0;
}
queen(1,n);
printf("\n");
return 0;
}
void print(int n)
{
int i,j;
printf("\n\nSolution %d:\n\n",++count);
for(i=1;i<=n;++i)
printf(" %d",i);
for(i=1;i<=n;++i)
{
printf("\n%d",i);
for(j=1;j<=n;++j)
{
if(board[i]==j)
printf(" Q");
else
printf(" *");
}
}
}
int place(int row,int column)
{
int i;
for(i=1;i<=row-1;++i)
{
if(board[i]==column)
return 0;
else
if(abs(board[i]-column)==abs(i-row))
return 0;
}
return 1;
}
void queen(int row,int n)
{
int column;
for(column=1;column<=n;++column)
{
if(place(row,column))
{
board[row]=column;
if(row==n)
print(n);
else
queen(row+1,n);
}
}
}