-
Notifications
You must be signed in to change notification settings - Fork 34
/
N-knight VishalRastogi.cpp
140 lines (119 loc) · 1.84 KB
/
N-knight 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
#include<iostream>
#include<time.h>
using namespace std;
bool IsSafe(int arr[100][100],int n,int x,int y)
{
bool left = true, right = true, up = true, down = true;
if(x+2>n-1)
{
right = false;
}
if(x-2<0)
{
left = false;
}
if(y+2>n-1)
{
down = false;
}
if(y-2<0)
{
up = false;
}
if(right)
{
if(arr[y-1][x+2] ==1 || arr[y+1][x+2] == 1)
{
return false;
}
}
if(left)
{
if(arr[y-1][x-2] ==1 || arr[y+1][x-2] == 1)
{
return false;
}
}
if(up)
{
if(arr[y-2][x+1] ==1 || arr[y-2][x-1] == 1)
{
return false;
}
}
if(down)
{
if(arr[y+2][x+1] ==1 || arr[y+2][x-1] == 1)
{
return false;
}
}
return true ;
}
int NKnight(int arr[100][100],int n,int x,int y,int i)
{
//base condition
if(i == n )
{
//cout<<"x="<<x<<" y="<<y<<" i="<<i<<endl;
for(int j = 0;j<n;j++)
{
for(int k = 0;k<n;k++)
{
//cout<<arr[j][k]<<" ";
if(arr[j][k] == 1)
{
cout<<"{"<<j<<"-"<<k<<"} ";
}
}
//cout<<endl;
}
cout<<" ";
//cout<<endl<<endl;
return 1;
}
if( x==n && y == n-1 )
{
//cout<<"x="<<x<<" y="<<y<<" i="<<i<<endl;
return 0;
}
if(x == n)
{
//cout<<"x="<<x<<" y="<<y<<" i="<<i<<endl;
return NKnight(arr,n,0,y+1,i);
}
int sum = 0;
for(int j = y;j<n;j++)
{
int k;
if(j == y)
{
k = x;
}
else
{
k = 0;
}
for(;k<n;k++)
{
if(IsSafe(arr,n,k,j))
{
//cout<<"x="<<j<<" y="<<k<<" i="<<i<<endl;
arr[j][k] = 1;
sum += NKnight(arr,n,k+1,j,(i+1));
arr[j][k] = 0;
}
}
}
return sum;
}
int main()
{
int n;
cin>>n;
int arr[100][100] = {0};
//clock_t start = clock();
cout<<NKnight(arr,n,0,0,0)<<endl;
//clock_t end = clock();
//cout<<end - start<<endl;
}