-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathN-Queens.cpp
More file actions
53 lines (51 loc) · 1.29 KB
/
N-Queens.cpp
File metadata and controls
53 lines (51 loc) · 1.29 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
class Solution
{
public:
vector<vector<string>> solveNQueens(int n)
{
vector<vector<int>> q;
for (int i = 0; i < n; ++i)
{
q.push_back(vector<int>({i}));
}
for (int i = 1; i < n; ++i)
{
vector<vector<int>> temp;
for (vector<int>& x : q)
{
for (int p = 0; p < n; ++p)
{
int j = 0;
for (; j < i; ++j)
{
if (x[j] == p || x[j] + j == p + i || x[j] - j == p - i)
{
break;
}
}
if (j == i)
{
temp.push_back(x);
temp.back().push_back(p);
}
}
}
q.swap(temp);
}
vector<string> s(n, string(n, '.'));
for (size_t i = 0; i < n; ++i)
{
s[i][i] = 'Q';
}
vector<vector<string>> result;
for (auto& x : q)
{
result.push_back(vector<string>());
for (auto i : x)
{
result.back().push_back(s[i]);
}
}
return result;
}
};