-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathn-queens.cpp
45 lines (43 loc) · 1.16 KB
/
n-queens.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
class Solution {
public:
vector <vector<string> > ans;
int tot;
void dfs(vector <string> & store) {
if(store.size() == tot) {
ans.push_back(store);
return ;
}
int r = store.size(), c = tot;
for(int i = 0; i < tot; i++) {
bool mark = true;
for(int x = 0; x < r; x++) { // vertical
if(store[x][i] != '.') {
mark = false;
break;
}
if(i-(r-x) >= 0 && store[x][i-(r-x)] != '.') {
mark = false;
break;
}
if(i+(r-x) < tot && store[x][i+(r-x)] != '.') {
mark = false;
break;
}
}
if(mark) {
string biu(tot, '.');
biu[i] = 'Q';
store.push_back(biu);
dfs(store);
store.pop_back();
}
}
}
vector<vector<string> > solveNQueens(int n) {
ans.clear();
tot = n;
vector <string> temp;
dfs(temp);
return ans;
}
};