Skip to content

Commit 4990734

Browse files
committed
[BOJ] #13460. 구슬탈출 2 / 골드1 / 90분 / 힌트,성공
1 parent 18a88bd commit 4990734

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
import sys
2+
from collections import deque
3+
input = sys.stdin.readline
4+
5+
# 보드의 크기 입력
6+
N, M = map(int, input().split()) # N: 세로, M: 가로
7+
rect_board = [list(map(str, input().strip())) for _ in range(N)] # 직사각형 보드
8+
9+
# BFS 탐색 방향 (상, 우, 하, 좌)
10+
directions = [(-1, 0), (0, 1), (1, 0), (0, -1)]
11+
12+
# 빨간 구슬(R)과 파란 구슬(B)의 초기 위치 찾기
13+
rx, ry, bx, by = 0, 0, 0, 0
14+
for i in range(N):
15+
for j in range(M):
16+
if rect_board[i][j] == 'R':
17+
rx, ry = i, j
18+
if rect_board[i][j] == 'B':
19+
bx, by = i, j
20+
21+
# BFS 탐색 준비
22+
queue = deque([(rx, ry, bx, by, 1)]) # (rx, ry, bx, by, depth)
23+
visited = set()
24+
visited.add((rx, ry, bx, by)) # 방문 체크
25+
26+
# 구슬 이동 함수
27+
def move(x, y, dx, dy):
28+
# 빨간 구슬과 파란 구슬을 보드에서 #이나 O를 만날 때까지 이동
29+
count = 0
30+
while rect_board[x + dx][y + dy] != '#' and rect_board[x][y] != 'O':
31+
x += dx
32+
y += dy
33+
count += 1 # 이동횟수
34+
return x, y, count
35+
36+
37+
# BFS 탐색
38+
while queue:
39+
rx, ry, bx, by, depth = queue.popleft()
40+
41+
# 10번을 초과했다면 실패
42+
if depth > 10:
43+
print(-1)
44+
exit()
45+
46+
# BFS 4방향 탐색
47+
for dx, dy in directions:
48+
# 빨간 구슬과 파란 구슬 이동
49+
nrx, nry, r_count = move(rx, ry, dx, dy)
50+
nbx, nby, b_count = move(bx, by, dx, dy)
51+
52+
# 파란 구슬이 구멍에 빠지면 실패 -> 다음 방향 탐색
53+
if rect_board[nbx][nby] == 'O':
54+
continue
55+
56+
# 빨간 구슬이 구멍에 빠지면 성공
57+
if rect_board[nrx][nry] == 'O':
58+
print(depth)
59+
exit()
60+
61+
# 두 구슬이 겹칠 경우, 더 많이 이동한 구슬을 한 칸 뒤로
62+
if nrx == nbx and nry == nby:
63+
if r_count > b_count:
64+
nrx -= dx
65+
nry -= dy
66+
else:
67+
nbx -= dx
68+
nby -= dy
69+
70+
71+
# 방문하지 않은 경우에만 큐에 추가
72+
if (nrx, nry, nbx, nby) not in visited:
73+
queue.append((nrx, nry, nbx, nby, depth + 1))
74+
visited.add((nrx, nry, nbx, nby))
75+
# 10번 이내에 성공하지 못했다면 -1 출력
76+
77+
print(-1)

0 commit comments

Comments
 (0)