-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path51.n-queens.cpp
More file actions
63 lines (53 loc) · 1.57 KB
/
51.n-queens.cpp
File metadata and controls
63 lines (53 loc) · 1.57 KB
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
class Solution {
public:
vector<vector<string>> solveNQueens(int n) {
vector<int> q_pos (n, -1);
int curr = 0;
vector<vector<string>> chess;
bool isFound;
string dot = "";
for(int i=0; i<n; i++)
dot += ".";
vector<string> res(n, dot);
while(curr > -1){
cout<<curr<<endl;
isFound = false;
for(int i=q_pos[curr]+1; i<n; i++){
cout<<"In for "<<i<<endl;
isFound = isValid(q_pos, i, curr);
if(isFound){
q_pos[curr] = i;
curr++;
break;
}
}
if(curr == n)
{
print(q_pos);
for(int k=0; k<q_pos.size(); k++)
res[k][q_pos[k]] = 'Q';
chess.push_back(res);
for(int k=0; k<q_pos.size(); k++)
res[k][q_pos[k]] = '.';
curr--;;
}
if(!isFound){
q_pos[curr] = -1;
curr--;
}
}
return chess;
}
void print(vector<int> q_pos){
for(auto i : q_pos)
cout<<i<<"\t";
cout<<endl;
}
bool isValid(vector<int> q_pos, int i, int curr){
for(int k=0; k<q_pos.size(); k++){
if(i == q_pos[k] || (curr-k) == abs(q_pos[k] - i))
return false;
}
return true;
}
};