-
Notifications
You must be signed in to change notification settings - Fork 0
/
nqueen.cpp
83 lines (60 loc) · 1.53 KB
/
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
#include <iostream>
#include <utility>
#include <stack>
using namespace std;
bool isSafe(int row, int col, stack<pair<int, int>> queens){
int q_row, q_col;
pair<int, int> curr;
while(!queens.empty()){
curr=queens.top();
queens.pop();
q_row=curr.first;
q_col=curr.second;
if(col==q_col)
return false;
if(row-col==q_row-q_col)
return false;
if(row+col==q_row+q_col)
return false;
}
return true;
}
bool get_valid_col(int row, int n, stack<pair<int, int>> &queens){
bool check;
if(row==n)
return true;
for(int i=0; i<n; i++){
if(isSafe(row, i, queens)){
queens.push(make_pair(row, i));
check=get_valid_col(row+1, n, queens);
if(check)
return true;
queens.pop();
}
}
return false;
}
void getPosition(int n, stack<pair<int, int>> &queens){
bool check;
for(int i=0; i<n; i++){
queens.push(make_pair(0, i));
if(get_valid_col(1, n, queens))
break;
queens.pop();
}
}
int main(){
int n;
cin>>n;
stack<pair<int, int>> queens;
getPosition(n, queens);
if(queens.empty())
cout<<"not possible";
else
cout<<"possible"<<endl;
while(!queens.empty()){
cout<<queens.top().first<<" "<<queens.top().second<<endl;
queens.pop();
}
return 0;
}