💡 bfs 문제 중 정말 어려웠던 문제였다.. 풀이법을 빠르게 생각하는 것이 중요하다!

import sys
from collections import deque
input = sys.stdin.readline
R, C = map(int, input().split(' '))
graph = [list(input().rstrip()) for _ in range(R)]
# 상하좌우
dx = [0,0,-1,1]
dy = [1,-1,0,0]
dq = deque()
jihun_x, jihun_y = 0, 0
# 불 위치 저장
for i in range(R):
for j in range(C):
if graph[i][j] == 'J':
jihun_x , jihun_y = j, i
elif graph[i][j] == 'F':
dq.append((j,i, 'F', 0))
# 지훈 위치 저장
dq.append((jihun_x,jihun_y,'J', 0))
def bfs():
cnt = 0
while dq:
x, y, val, cnt = dq.popleft()
if val == 'J' and (x == 0 or x == C-1 or y == 0 or y == R-1):
return cnt + 1
for idx in range(4):
nx = x + dx[idx]
ny = y + dy[idx]
if val == 'J':
if 0 <= nx < C and 0 <= ny < R and graph[ny][nx] == '.':
graph[ny][nx] = 'J'
dq.append((nx,ny,'J', cnt + 1))
else:
if 0 <= nx < C and 0 <= ny < R and graph[ny][nx] == '.':
graph[ny][nx] = 'F'
dq.append((nx,ny,'F', 0))
return "IMPOSSIBLE"
print(bfs())
< 핵심 코드 >
dq = deque()
jihun_x, jihun_y = 0, 0
# 불 위치 저장
for i in range(R):
for j in range(C):
if graph[i][j] == 'J':
jihun_x , jihun_y = j, i
elif graph[i][j] == 'F':
dq.append((j,i, 'F', 0))
# 지훈 위치 저장
dq.append((jihun_x,jihun_y,'J', 0))
if val == 'J' and (x == 0 or x == C-1 or y == 0 or y == R-1):
return cnt + 1
if val == 'J':
if 0 <= nx < C and 0 <= ny < R and graph[ny][nx] == '.':
graph[ny][nx] = 'J'
dq.append((nx,ny,'J', cnt + 1))
else:
if 0 <= nx < C and 0 <= ny < R and graph[ny][nx] == '.':
graph[ny][nx] = 'F'
dq.append((nx,ny,'F', 0))
while dq:
if val == 'J' and (x == 0 or x == C-1 or y == 0 or y == R-1):
return cnt + 1
( 생략 )
return "IMPOSSIBLE"
💡 코테스터디에서 나온 기발한 접근법
import sys
from collections import deque
input = sys.stdin.readline
r, c = map(int, input().split())
graph = []
q_j = deque()
q_f = deque()
visited_j = [[0] * c for _ in range(r)]
visited_f = [[0] * c for _ in range(r)]
move = [
[1, 0],
[-1, 0],
[0, 1],
[0, -1]
]
for i in range(r):
temp = list(input())
for j in range(len(temp)):
if temp[j] == "J":
q_j.append((i, j))
visited_j[i][j] = 1
elif temp[j] == "F":
q_f.append((i, j))
visited_f[i][j] = 1
graph.append(temp)
def bfs():
while q_f:
x, y = q_f.popleft()
for i in range(4):
nx, ny = x + move[i][0], y + move[i][1]
if 0 <= nx < r and 0 <= ny < c:
if not visited_f[nx][ny] and graph[nx][ny] != "#":
visited_f[nx][ny] = visited_f[x][y] + 1
q_f.append((nx, ny))
while q_j:
x, y = q_j.popleft()
for i in range(4):
nx, ny = x + move[i][0], y + move[i][1]
if 0 <= nx < r and 0 <= ny < c:
if graph[nx][ny] != "#" and not visited_j[nx][ny]:
if not visited_f[nx][ny] or visited_f[nx][ny] > visited_j[x][y] + 1:
visited_j[nx][ny] = visited_j[x][y] + 1
q_j.append((nx, ny))
else:
return visited_j[x][y]
return "IMPOSSIBLE"
print(bfs())