-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProblem_08.12_solveNQueens.cc
57 lines (52 loc) · 1.04 KB
/
Problem_08.12_solveNQueens.cc
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
#include <string>
#include <vector>
using namespace std;
class Solution
{
public:
bool check(vector<int>& record, int i, int j)
{
for (int k = 0; k < i; k++)
{
if (record[k] == j || std::abs(record[k] - j) == std::abs(i - k))
{
return false;
}
}
return true;
}
void makeNQueen(vector<int>& record, vector<vector<string>>& ans)
{
int n = record.size();
vector<string> nQueen(n, string(n, '.'));
for (int i = 0; i < n; i++)
{
nQueen[i][record[i]] = 'Q';
}
ans.emplace_back(nQueen);
}
void f(int i, vector<int>& record, vector<vector<string>>& ans)
{
if (i == record.size())
{
makeNQueen(record, ans);
return;
}
for (int j = 0; j < record.size(); j++)
{
if (check(record, i, j))
{
record[i] = j;
f(i + 1, record, ans);
record[i] = 0;
}
}
}
vector<vector<string>> solveNQueens(int n)
{
vector<vector<string>> ans;
vector<int> record(n);
f(0, record, ans);
return ans;
}
};