-문제: https://www.acmicpc.net/problem/13460
-정답풀이:
N, M = map(int, input().split())
B = [list(input().rstrip()) for _ in range(N)] # Board
dx = [-1, 1, 0, 0] # x축 움직임
dy = [0, 0, -1, 1] # y축 움직임
queue = [] # BFS : queue 활용
# Red(rx,ry)와 Blue(bx,by)의 탐사 여부 체크
visited = [[[[False] * M for _ in range(N)] for _ in range(M)] for _ in range(N)]
def pos_init():
rx, ry, bx, by = 0, 0, 0, 0 # 초기화
for i in range(N):
for j in range(M):
if B[i][j] == 'R':
rx, ry = i, j
elif B[i][j] == 'B':
bx, by = i, j
# 위치 정보와 depth(breadth 끝나면 +1)
queue.append((rx, ry, bx, by, 1))
visited[rx][ry][bx][by] = True
def move(x, y, dx, dy):
cnt = 0 # 이동 칸 수
# 다음이 벽이거나 현재가 구멍일 때까지
while B[x+dx][y+dy] != '#' and B[x][y] != 'O':
x += dx
y += dy
cnt += 1
return x, y, cnt
def solve():
pos_init() # 시작 조건
while queue: # BFS : queue 기준
rx, ry, bx, by, depth = queue.pop(0)
if depth > 10: # 실패 조건
break
for i in range(4): # 4방향 이동 시도
nrx, nry, rcnt = move(rx, ry, dx[i], dy[i]) # Red
nbx, nby, bcnt = move(bx, by, dx[i], dy[i]) # Blue
if B[nbx][nby] != 'O': # 실패 조건이 아니면
if B[nrx][nry] == 'O': # 성공 조건
print(depth)
return
if nrx == nbx and nry == nby: # 겹쳤을 때
if rcnt > bcnt: # 이동거리가 많은 것을
nrx -= dx[i] # 한 칸 뒤로
nry -= dy[i]
else:
nbx -= dx[i]
nby -= dy[i]
# breadth 탐색 후, 탐사 여부 체크
if not visited[nrx][nry][nbx][nby]:
visited[nrx][nry][nbx][nby] = True
# 다음 depth의 breadth 탐색 위한 queue
queue.append((nrx, nry, nbx, nby, depth+1))
print(-1) # 실패 시
solve()
참고한 블로그: https://wlstyql.tistory.com/72
백준 알고리즘 13460 (구슬 탈출 1,2) - python
[문제] 백준 알고리즘 13459 (구슬 탈출) > https://www.acmicpc.net/problem/13459 13459번: 구슬 탈출 첫 번째 줄에는 보드의 세로, 가로 크기를 의미하는 두 정수 N, M (3 ≤ N, M ≤ 10)이 주어진다. 다음 N..
wlstyql.tistory.com
-문제 해결방법 생각해본 거:
'백준 > Search' 카테고리의 다른 글
[백준/bfs] 1707번: 이분 그래프 (0) | 2022.02.22 |
---|---|
[백준/bfs] 1389번: 케빈 베이컨의 6단계 법칙 (0) | 2022.02.22 |
[백준/bfs] 16236번: 아기 상어(다시) (0) | 2022.02.21 |
[백준/bfs] 11725번: 트리의 부모 찾기 (0) | 2022.02.20 |
[백준/bfs] 2583: 영역 구하기 (0) | 2022.02.20 |