-
Notifications
You must be signed in to change notification settings - Fork 0
/
NQueens.cpp
61 lines (61 loc) · 1.32 KB
/
NQueens.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
/*
Given N queens and these queens needs to be placed in n x n matrix such that :-
No two queens are placed in the same row.
No two queens are placed in the same column.
No two queens are in the same diagonal
We can solve this problem using backtracking, whenever we place a new queen in a particular row we backtrack and check if all the conditions are being satisfied if we do so
*/
#include <bits/stdc++.h>
using namespace std ;
class NQueen
{
int n ;
vector<int> x ;
public :
NQueen(int n)
{
this->n = n ;
x.resize(n+1,0) ;
}
bool place(int k , int i)
{
for(int j=1; j<=k-1 ; j++)
{
if(x[j]==i || abs(j-k)==abs(x[j]-i))
return false;
}
return true ;
}
void NQ(int k)
{
for(int i=1; i<=n ; i++)
{
if(place(k,i))
{
x[k]=i ;
if(k==n)
{
for(int i=1 ; i<=n ; i++)
{
for(int j=1 ; j<=n ; j++)
{
if(x[i]==j) cout << " Q " ;
else cout << " * " ;
}
cout << endl ;
}
cout << endl;
return ;
}
else NQ(k+1);
}
}
}
};
int main()
{
int n;
cout << "Enter number of queens :- " ; cin >> n ;
NQueen N(n);
N.NQ(1) ;
}