-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathNqueen.cpp
83 lines (71 loc) · 940 Bytes
/
Nqueen.cpp
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
#include<iostream>
using namespace std;
//Problem statement- Place n number of queens(ones) in a nXn matrix of zeroes
bool isSafeToPut(int sol[][10],int i,int j,int n)
{
for(int k=0;k<n;k++)
{
if(sol[k][j] || sol[i][k])
{
return false;
}
}
int row=i,col=j;
while(row>=0 && col>=0)
{
if(sol[row][col])
{
return false;
}
row--;
col--;
}
row=i,col=j;
while(row>=0 && col<n)
{
if(sol[row][col])
{
return false;
}
row--;
col++;
}
return true;
}
bool nqueen(int sol[][10],int i,int n)
{
if(i==n)
{
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
cout<<sol[i][j]<<" ";
}
cout<<endl;
}
cout<<endl;
return false;
}
for(int j=0;j<n;j++)
{
if(isSafeToPut(sol,i,j,n))
{
sol[i][j]=1;
if(nqueen(sol,i+1,n))
{
return true;
}
sol[i][j]=0;
}
}
return false;
}
int main()
{
int sol[10][10]={0};
int n;
cin>>n;
nqueen(sol,0,n);
return 0;
}