-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path100000608-03.cpp
57 lines (50 loc) · 1.1 KB
/
100000608-03.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
#include <cstdio>
#include <vector>
#define MAXN 12
using namespace std;
int n;
vector<int> ans;
bool is_existed[MAXN] = {}, has_ans = false;
void output()
{
for (int i = 0 ; i < n; i++)
printf(i == n - 1 ? "%d\n" : "%d ", ans[i]);
}
// 判断前 n 个元素是否合法,即是否符合 8 皇后问题
bool is_valid(int n)
{
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++)
if (j - i == ans[j] - ans[i] ||
i - j == ans[j] - ans[i])
return false;
return true;
}
void dfs(int now_cnt)
{
// 递归边界
if (now_cnt == n && is_valid(n))
{
output();
has_ans = true;
return;
}
// 循环分岔口
for (int i = 1; i <= n; i++)
if (!is_existed[i])
{
if (!is_valid(now_cnt)) return; // 剪枝
ans.push_back(i);
is_existed[i] = true;
dfs(now_cnt + 1);
ans.pop_back();
is_existed[i] = false;
}
}
int main()
{
scanf("%d", &n);
dfs(0);
if (!has_ans) printf("no solute!");
return 0;
}