-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathNqueen.cpp
More file actions
65 lines (56 loc) · 694 Bytes
/
Copy pathNqueen.cpp
File metadata and controls
65 lines (56 loc) · 694 Bytes
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
#include<bits/stdc++.h>
using namespace std;
int a[1000][1000]={0};
int n;
int safe(int r,int c)
{
int i,j;
for(i=0;i<c;i++)
if(a[r][i]==1)
return 0;
for(i=0,j=0;i<r && j<c;i++,j++)
if(a[i][j]==1)
return 0;
for(i=n-1,j=0;i>r && j<c;i--,j++)
if(a[i][j]==1)
return 0;
return 1;
}
void print()
{
int i,j;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
cout<<a[i][j]<<" ";
}
cout<<endl;
}
}
int foo(int c)
{
int i;
if(c>=n)
return 1;
for(i=0;i<n;i++)
{
if(a[i][c]==0 && safe(i,c))
{
a[i][c]=1;
if(foo(c+1))
return 1;
a[i][c]=0;
}
}
return 0;
}
int main()
{
int i,j;
cin>>n;
if(foo(0))
print();
else
cout<<"No solution exist";
}