forked from Nivedpv2004/C-PROGRAMING
-
Notifications
You must be signed in to change notification settings - Fork 0
/
N-Queen.c
77 lines (77 loc) · 1 KB
/
N-Queen.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
#include<stdio.h>
#include<conio.h>
bool isSafe(int board[][10], int row, int col, int n)
{
for(int i=0;i<col;i++)
{
if(board[row][i] == 1)
{
return false;
}
}
for(int i=row,j=col;i>=0 && j>=0;i--,j--)
{
if(board[i][j] ==1)
{
return false;
}
}
for(int i=row,j=col;i<n && j>=0;i++,j--)
{
if(board[i][j] ==1)
{
return false;
}
}
return true;
}
bool nQueen(int board[][10], int col, int n)
{
if(col>=n)
{
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
cout<<board[i][j]<<" ";
}
cout<<endl;
}
return true;
}
for(int i=0;i<n;i++)
{
if(isSafe(board,i,col,n))
{
board[i][col]=1;
if(nQueen(board,col+1,n))
{
return true;
}
board[i][col]=0;
}
}
return false;
}
int main()
{
int n;
int board[10][10]={0};
scanf("%d",&n);
bool check = nQueen(board,0,n);
if(check == false)
printf("-1");
else
{
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
printf("%d ",board[i][j]);
}
printf("\n");
}
}
getch();
return 0;
}