1+ from collections import deque
2+ import sys
3+
4+ input = sys .stdin .readline
5+
6+ n , m = map (int , input ().split ()) # 행, 열
7+
8+ board = [list (input ().rstrip ()) for _ in range (n )]
9+ visited = []
10+
11+ dx = [1 , - 1 , 0 , 0 ]
12+ dy = [0 , 0 , - 1 , 1 ]
13+ cnt = 0
14+
15+
16+ def getPos ():
17+ rx , ry , bx , by = 0 , 0 , 0 , 0
18+ for x in range (n ):
19+ for y in range (m ):
20+ if board [x ][y ] == "R" :
21+ rx , ry = x , y
22+ if board [x ][y ] == "B" :
23+ bx , by = x , y
24+ return rx , ry , bx , by
25+
26+
27+ def move (x , y , dx , dy ):
28+ cnt = 0
29+ # 이동하는 위치가 벽이아니고, 구멍에 들어가지 않을 동안 반복
30+ while board [x + dx ][y + dy ] != "#" and board [x ][y ] != "O" :
31+ x += dx
32+ y += dy
33+ cnt += 1
34+ return x , y , cnt
35+
36+
37+ def bfs ():
38+ rx , ry , bx , by = getPos ()
39+
40+ q = deque ()
41+ q .append ((rx , ry , bx , by , 1 ))
42+ visited .append ((rx , ry , bx , by ))
43+
44+ while q :
45+ rx , ry , bx , by , result = q .popleft ()
46+
47+ if result > 10 :
48+ break
49+
50+ for i in range (4 ):
51+ nrx , nry , rcnt = move (rx , ry , dx [i ], dy [i ])
52+ nbx , nby , bcnt = move (bx , by , dx [i ], dy [i ])
53+
54+ # 파란 구슬이 구멍에 들어갈 경우
55+ if board [nbx ][nby ] == "O" :
56+ continue
57+
58+ # 빨간 구슬이 들어갈 경우 성공
59+ if board [nrx ][nry ] == "O" :
60+ print (result )
61+ return
62+
63+ # 둘이 겹쳐있을경우 더 많이 이동한녀석을 1칸 뒤로 보낸다.
64+ if nrx == nbx and nry == nby :
65+ if rcnt > bcnt :
66+ nrx -= dx [i ]
67+ nry -= dy [i ]
68+ else :
69+ nbx -= dx [i ]
70+ nby -= dy [i ]
71+
72+ # 탐색하지 않은 방향 탐색
73+ if (nrx , nry , nbx , nby ) not in visited :
74+ visited .append ((nrx , nry , nbx , nby ))
75+ q .append ((nrx , nry , nbx , nby , result + 1 ))
76+ print (- 1 )
77+
78+
79+ bfs ()
0 commit comments