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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
| #include <iostream>
#include <list>
#define INF 2000000000;
using namespace std;
struct node {
pair<int, int> r;
pair<int, int> b;
int d;
};
int map[10][10], n, m, os[4][2] = { {-1,0}, {0,1}, {1, 0}, {0,-1} };
pair<int, int> h, r, b;
bool visit[10][10][10][10];
list<node> l;
int bfs();
int min(int a, int b) {
return a < b ? a : b;
}
int main() {
cin >> n >> m;
for (int i = 0; i < n; i++) {
string a;
cin >> a;
for (int j = 0; j < m; j++) {
map[i][j] = a[j];
switch (map[i][j]) {
case 'R':
r = { i,j };
break;
case 'B':
b = { i,j };
break;
case 'O':
h = { i,j };
}
}
}
cout << bfs();
}
int bfs() {
visit[r.first][r.second][b.first][b.second] = true;
l.push_back({ {r.first, r.second}, {b.first, b.second}, 0 });
int ans = INF;
while (!l.empty()) {
node cur = l.front();
l.pop_front();
for (int i = 0; i < 4; i++) {
int rr = cur.r.first, rc = cur.r.second, br = cur.b.first, bc = cur.b.second, nd = cur.d + 1;
bool rf = true;
if (i % 2 == 0 && rc == bc) {
if (i == 0 && rr > br)
rf = false;
else if (i == 2 && rr < br)
rf = false;
}
else if (i % 2 == 1 && rr == br) {
if (i == 1 && bc > rc)
rf = false;
else if (i == 3 && bc < rc)
rf = false;
}
bool rh = false, bh = false;
if (rf) {
while (map[rr + os[i][0]][rc + os[i][1]] != '#') {
rr += os[i][0];
rc += os[i][1];
if (map[rr][rc] == 'O') {
rh = true;
rr = rc = -1;
break;
}
}
while (map[br + os[i][0]][bc + os[i][1]] != '#' && (br + os[i][0] != rr|| bc + os[i][1] != rc)) {
br += os[i][0];
bc += os[i][1];
if (map[br][bc] == 'O') {
bh = true;
break;
}
}
}
else {
while (map[br + os[i][0]][bc + os[i][1]] != '#') {
br += os[i][0];
bc += os[i][1];
if (map[br][bc] == 'O') {
bh = true;
br = bc = -1;
break;
}
}
while (map[rr + os[i][0]][rc + os[i][1]] != '#' && (rr + os[i][0] != br || rc + os[i][1] != bc)) {
rr += os[i][0];
rc += os[i][1];
if (map[rr][rc] == 'O') {
rh = true;
break;
}
}
}
if (rh && !bh)
ans = min(ans, nd);
else if (!rh && !bh && !visit[rr][rc][br][bc]) {
visit[rr][rc][br][bc] = true;
l.push_back({ {rr, rc}, {br, bc}, nd });
}
}
}
return ans == 2000000000 ? -1 : ans;
}
|