forked from IOSD/IOSD-NITK-HacktoberFest-Meetup-2019
-
Notifications
You must be signed in to change notification settings - Fork 0
/
nqueen VishalRastogi.cpp
149 lines (131 loc) · 2.23 KB
/
nqueen VishalRastogi.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
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
#include<iostream>
#include<time.h>
using namespace std;
/*
bool IsSafe(int arr[100][100],int x,int y,int n)
{
for(int i = x, j = 0;(i<n && j<n) (i>0 && j>0); j++)
{
if(arr[j][i] == 1 )
{
if(j!=y && i!=x)
{
return false;
}
}
}
for(int i = 0, j = y;(i<n && j<n)&& (i>0 && j>0); i++)
{
if(arr[j][i] == 1 )
{
if(j!=y && i!=x)
{
return false;
}
}
}
for(int i = x , j = y ;(i<n && j<n)&& (i>0 && j>0); i++,j++)
{
if(arr[j][i] == 1 )
{
if(j!=y && i!=x)
{
return false;
}
}
}
for(int i = x , j = y ;(i<n && j<n)&& (i>0 && j>0); i--,j--)
{
if(arr[j][i] == 1 )
{
if(j!=y && i!=x)
{
return false;
}
}
}
for(int i = x, j = y ;(i<n && j<n)&& (i>0 && j>0); i--,j++)
{
if(arr[j][i] == 1 )
{
if(j!=y && i!=x)
{
return false;
}
}
}
for(int i = x, j = y ;(i<n && j<n)&& (i>0 && j>0); i++,j--)
{
if(arr[j][i] == 1 )
{
if(j!=y && i!=x)
{
return false;
}
}
}
return true;
}
*/
bool IsSafe2(int arr[100][100],int n,int x,int y){
int check[8][2] = {{1,0},{-1,0},{0,1},{0,-1},{1,1},{1,-1},{-1,1},{-1,-1}};
for(int k=0;k<8;k++){
for(int i=x+check[k][0],j=y+check[k][1];i<n && i>=0 &&j<n && j>=0;i+=check[k][0],j+=check[k][1]){
if(arr[i][j]==1){
return false;
}
}
}
return true;
}
int Nqueen(int arr[100][100],int n,int y)
{
if(y>=n)
{
/*
for(int i = 0;i<n;i++)
{
for(int j = 0;j<n;j++)
{
if(arr[i][j] == 1)
{
cout<<"{"<<i+1<<"-"<<j+1<<"}"<<" ";
}
}
}*/
/*for(int i = 0;i<n;i++)
{
for(int j = 0;j<n;j++)
{
//if(arr[i][j] == 1)
//{
cout<<arr[i][j];
//}
}
cout<<endl;
}*/
//cout<<" ";
return 1;
}
int sum =0;
for(int i = 0;i<n;i++)
{
if(IsSafe2(arr,n,i,y))
{
arr[i][y] = 1;
sum += Nqueen(arr,n,y+1);
arr[i][y] = 0;
}
}
return sum;
}
int main()
{
int n,count;
cin>>n;
clock_t start = clock();
int arr[100][100] = {0};
cout<<Nqueen(arr,n,0)<<endl;
clock_t end = clock();
//cout<<"time = "<<end-start;
}