UVa 932 - Checking the N-Queens Problem

contents

  1. 1. Problem
  2. 2. Sample Input
  3. 3. Sample Output
  4. 4. Solution

Problem

給定一個 N * N 的棋盤,檢查 N 個皇后是否衝突,如果存有衝突,嘗試移動一個皇后 (根據他所在的位置進行移動),如果可以有解則輸出,反之輸出找不到。

Sample Input

1
2
3
4
5
6
7
8
9
10
11
12
5
00X00
X0000
000X0
0X000
0000X
5
0X000
X0000
000X0
0X000
0000X

Sample Output

1
2
3
4
5
6
7
8
9
YES
NO
YES
00X00
X0000
000X0
0X000
0000X

Solution

窮舉所有移動可能,並且進行檢查即可。

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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#include <stdio.h>
#include <stdlib.h>
#include <algorithm>
using namespace std;
int check(int qx[], int qy[], int n) {
static int used[32] = {}, testcase = 0;
testcase++;
for (int i = 0; i < n; i++) {
if (used[qx[i]] == testcase) return 0;
used[qx[i]] = testcase;
}
testcase++;
for (int i = 0; i < n; i++) {
if (used[qy[i]] == testcase) return 0;
used[qy[i]] = testcase;
}
for (int i = 0; i < n; i++) {
for (int j = i+1; j < n; j++) {
if (abs(qx[i] - qx[j]) == abs(qy[i] - qy[j]))
return 0;
}
}
return 1;
}
int main() {
int n, cases = 0, tx, ty;
char g[32][32];
const int dx[] = {0, 0, 1, 1, 1, -1, -1, -1};
const int dy[] = {1, -1, 0, 1, -1, 0, 1, -1};
while (scanf("%d", &n) == 1) {
if (cases++) puts("");
for (int i = 0; i < n; i++)
scanf("%s", g[i]);
int qx[32], qy[32], m = 0;
for (int i = 0; i < n;i++) {
for (int j = 0; j < n; j++) {
if (g[i][j] == 'X')
qx[m] = i, qy[m] = j, m++;
}
}
if (check(qx, qy, m))
puts("YES");
else {
puts("NO");
int ok = 0;
for (int i = 0; i < m && !ok; i++) {
for (int j = 0; j < 8 && !ok; j++) {
tx = qx[i] + dx[j], ty = qy[i] + dy[j];
while (true) {
if (tx < 0 || ty < 0 || tx >= n || ty >= n)
break;
if (g[tx][ty] == '0') {
swap(tx, qx[i]), swap(ty, qy[i]);
if (check(qx, qy, m)) {
puts("YES");
ok = 1;
swap(g[qx[i]][qy[i]], g[tx][ty]);
for (int i = 0; i < n; i++)
puts(g[i]);
break;
}
swap(tx, qx[i]), swap(ty, qy[i]);
}
tx += dx[j], ty += dy[j];
}
}
}
if (!ok)
puts("NO");
}
}
return 0;
}
/*
5
00X00
X0000
000X0
0X000
0000X
5
0X000
X0000
000X0
0X000
0000X
*/