|
| 1 | +from collections import deque |
| 2 | +import sys |
| 3 | +""" |
| 4 | +1. ์ด๊ธฐํ |
| 5 | +- R,B ์ ์์น ์ขํ |
| 6 | +- ๋ฐฉ๋ฌธ ๋ฑ๋ก |
| 7 | +2. queue |
| 8 | +3. 4๋ฐฉ์ |
| 9 | +-> ํ๋ ๊ตฌ์ ๊ตฌ๋ฉ -> ์คํจ |
| 10 | +-> ๋นจ๊ฐ ๊ตฌ์ ๊ตฌ๋ฉ -> ์ฑ๊ณต |
| 11 | +-> ๋์ด ๊ฐ์ ์์น=> |
| 12 | +""" |
| 13 | + |
| 14 | +n, m = map(int, sys.stdin.readline().split()) |
| 15 | +board = [list(input().rstrip()) for _ in range(n)] |
| 16 | +visited = [] |
| 17 | + |
| 18 | +# ์ฐ,์ข,ํ,์ |
| 19 | +dx = [1 ,-1 , 0 ,0] |
| 20 | +dy = [0,0,-1,1] |
| 21 | + |
| 22 | +def get_RB_position(): # Red , Blue |
| 23 | + rx ,ry, bx , by = 0 , 0, 0, 0 |
| 24 | + for i in range(n): |
| 25 | + for j in range(m): |
| 26 | + if board[i][j] == "R" : |
| 27 | + rx , ry = i, j |
| 28 | + elif board[i][j] == "B": |
| 29 | + bx , by = i , j |
| 30 | + |
| 31 | + return rx ,ry, bx , by |
| 32 | + |
| 33 | +def move(x,y, dx , dy) : |
| 34 | + # ๋ฒฝ ๋๋ ๊ตฌ๋ฉ๊น์ง ์ด๋ |
| 35 | + # dx ,dy : ๋ฐฉํฅ |
| 36 | + shift_cnt = 0 |
| 37 | + while board[x + dx][y+dy] != "#" and board[x][y] != "O": |
| 38 | + x += dx |
| 39 | + y+= dy |
| 40 | + shift_cnt +=1 |
| 41 | + |
| 42 | + return x ,y, shift_cnt |
| 43 | + |
| 44 | + |
| 45 | +def bfs() : |
| 46 | + #1. ์ด๊ธฐํ |
| 47 | + rx , ry , bx , by = get_RB_position() |
| 48 | + queue = deque() |
| 49 | + queue.append((rx,ry, bx , by, 1)) # red ์ขํ , blue ์ขํ , ํ์ |
| 50 | + visited.append((rx,ry , bx,by)) |
| 51 | + |
| 52 | + while queue : |
| 53 | + rx,ry,bx,by,result= queue.popleft() |
| 54 | + # 10ํ ์ด๊ณผํด๋ ์๋์ค๋ฉด -1 ๋ฐํ |
| 55 | + if result > 10 : |
| 56 | + |
| 57 | + break |
| 58 | + |
| 59 | + for i in range(4): # |
| 60 | + crx , cry , r_shift = move(rx ,ry , dx[i], dy[i]) |
| 61 | + cbx , cby , b_shift = move(bx ,by, dx[i], dy[i]) |
| 62 | + |
| 63 | + # ๋ง์ฝ ํ๋๊ณต์ด ๊ตฌ๋ฉ์ ๋ค์ด๊ฐ๋ฉด ์คํจ |
| 64 | + if board[cbx][cby] == "O" : |
| 65 | + continue |
| 66 | + # ๋ง์ฝ ๋นจ๊ฐ ๊ณต์ด ๊ตฌ๋ฉ์ ๋ค์ด๊ฐ๋ฉด ์ฑ๊ณต |
| 67 | + if board[crx][cry] == "O" : |
| 68 | + print(result) |
| 69 | + return 0 |
| 70 | + # ๋ง์ฝ ๋ ๊ณต์ด ๊ฒน์น๋ฉด -> ๋ ๋ง์ด ์ด๋ํ ๊ณต์ด ๋ ์ ์ ์์ |
| 71 | + if cbx == crx and cry == cby : |
| 72 | + if r_shift > b_shift : # red ๊ฐ ๋ ๋ฉ๋ฆฌ ์์ |
| 73 | + crx -=dx[i] |
| 74 | + cry -= dy[i] |
| 75 | + else : |
| 76 | + cbx -=dx[i] |
| 77 | + cby -= dy[i] |
| 78 | + # ์ฒ์ ๋์ฐฉํ ์นธ์ธ ๊ฒฝ์ฐ |
| 79 | + if (crx , cry , cbx, cby) not in visited : |
| 80 | + visited.append((crx , cry , cbx, cby)) |
| 81 | + queue.append((crx , cry , cbx, cby , result +1)) |
| 82 | + print(-1) |
| 83 | + |
| 84 | +bfs() |
| 85 | + |
0 commit comments