-
Notifications
You must be signed in to change notification settings - Fork 0
/
LP1_DAA_A2_nQueen.cpp
88 lines (64 loc) · 1.92 KB
/
LP1_DAA_A2_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
84
85
86
87
88
#include<bits/stdc++.h>
using namespace std;
void print(int n,int col[])
{
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(col[i]==j) cout<<i+1<<" ";
else cout<<"0 ";
}
cout<<"\n";
}
cout<<"\n";
}
bool place(int queen,int c,int col[])
{
int j=0;
while(j<queen)
{
if(col[j]==c || abs(col[j]-c)==abs(j-queen))
return false;
j++;
}
return true;
}
bool nqueen(int queen,int n,int col[])
{
int fl=0;
for(int i=0;i<n;i++)
{
if(place(queen,i,col))
{
col[queen]=i;
cout<<"Placing Queen "<<queen+1<<"\n";
print(n,col);
if(queen==n-1) return true;
if(nqueen(queen+1,n,col))
return true;
col[queen]=-1;
cout<<"Backtracking Queen "<<queen+1<<"\n";
print(n,col);
fl=1;
}
}
if(!fl)
cout<<"Unable to place Queen "<<queen+1<<"\n\n";
return false;
}
int main()
{
int n;
cout<<"Enter Size of chessboard : ";
cin>>n;
if(n<=3)
{
cout<<"\nSize should be more than 3\n";
return 0;
}
int col[n];
for(int i=0;i<n;i++) col[i]=-1;
nqueen(0,n,col);
return 0;
}