/
BAEKJOON 13460
109 lines (101 loc) · 2.39 KB
/
BAEKJOON 13460
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
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class Main {
static int N, M, ry, rx, by, bx;
static char[][] map;
static Queue<Ball> q = new LinkedList<>();
static int[] dy = { -1, 1, 0, 0 }, dx = { 0, 0, -1, 1 };
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
map = new char[N][M];
for (int i = 0; i < N; i++) {
map[i] = br.readLine().toCharArray();
for (int j = 0; j < M; j++) {
if (map[i][j] == 'R') {
ry = i;
rx = j;
map[i][j] = '.';
} else if (map[i][j] == 'B') {
by = i;
bx = j;
map[i][j] = '.';
}
}
}
q.offer(new Ball(ry, rx, by, bx, 0));
bfs();
}
private static void bfs() {
while (!q.isEmpty()) {
Ball b = q.poll();
if (b.cnt > 10) { // 10회 이상이므로 실패
System.out.println(-1);
return;
}
if(map[b.by][b.bx] == 'O') // 파란공이 골인한경우
continue;
if(map[b.ry][b.rx] == 'O') { // 빨간공이 골인한 경우
System.out.println(b.cnt);
return;
}
for (int i = 0; i < 4; i++) {
by = b.by;
bx = b.bx;
while (true) {
by += dy[i];
bx += dx[i];
if (map[by][bx] == '#') {
by -= dy[i];
bx -= dx[i];
break;
}
if (map[by][bx] == 'O') {
break;
}
}
ry = b.ry;
rx = b.rx;
while (true) {
ry += dy[i];
rx += dx[i];
if (map[ry][rx] == '#') {
ry -= dy[i];
rx -= dx[i];
break;
}
if (map[ry][rx] == 'O') {
break;
}
}
if(ry == by && rx == bx && map[ry][rx] != 'O') {
int red = Math.abs(b.ry - ry) + Math.abs(b.rx - rx);
int blue = Math.abs(b.by - by) + Math.abs(b.bx - bx);
if(red > blue) { //레드가 크면 레드가 늦게 온거
ry -= dy[i];
rx -= dx[i];
}else if(blue > red) {
by -= dy[i];
bx -= dx[i];
}
}
q.offer(new Ball(ry, rx, by, bx, b.cnt+1));
}
}
}
static class Ball {
int ry, rx, by, bx, cnt;
public Ball(int ry, int rx, int by, int bx, int cnt) {
this.ry = ry;
this.rx = rx;
this.by = by;
this.bx = bx;
this.cnt = cnt;
}
}
}