[๋ฐฑ์ค] ๋ฒ. ๋ถ! ๐ฅ ๋ฐ๋ก๊ฐ๊ธฐ
ํ์ถ
์ ์๊ฐํ๊ณ ๋๊ฐ์ด ๊ตฌํํ๋๋ฐ ์์ธ ์ฒ๋ฆฌ๊ฐ ํ๋ค์๋ค. (10๋ฒ๋ง์ ํต๊ณผํ๋ฏ) -> ์ค์ ์ํ์์ ํ
์คํธ์ผ์ด์ค์์ด ํต๊ณผํ ์ ์์๊น? ๐ฅบ์งํ์ด
์ ๋ถ
์ ์์๋๋ก queue
์ ๋ด๋๋ค.bfs
๋ฅผ ํ๋ค.O(r*c)
from collections import deque
import sys
input = sys.stdin.readline
# ํ์ถ
def escape(position):
while position:
x, y = position.popleft()
# 2. ์งํ์ด๋ ๋ฏธ๋ก์ ๊ฐ์ฅ์๋ฆฌ์ ์ ํ ๊ณต๊ฐ ์ด์๋จ์์ ๊ฐ์ ๋์๋ง ํ์ถํ ์ ์๋ค.
if maze[x][y] == 'J' and not (1 <= x < r - 1 and 1 <= y < c - 1):
return time[x][y] + 1
# ์ด๋
for d in range(4):
nx = x + dx[d]
ny = y + dy[d]
# ๊ฐ ์ ์๋ ๊ณณ์ด๋ฉด ์ด๋
if 0 <= nx < r and 0 <= ny < c and maze[nx][ny] != '#':
# ์งํ์ด๊ฐ ์๊ฐ๋ ๊ณณ์ด๋ฉด
if maze[x][y] == 'J' and maze[nx][ny] == '.' and maze[nx][ny] != 'J':
time[nx][ny] = time[x][y] + 1 # ๊ฑธ๋ฆฌ๋ ์๊ฐ
position.append((nx, ny))
maze[nx][ny] = 'J' # ๋ฐฉ๋ฌธ์ฒ๋ฆฌ
# ๋ถ!์ด๊ณ ์๊ฐ๋ ๊ณณ์ด๋ฉด
if maze[x][y] == 'F' and maze[nx][ny] != 'F':
position.append((nx, ny))
maze[nx][ny] = 'F'
return "IMPOSSIBLE"
r, c = map(int, input().split())
maze = [list(input().strip()) for _ in range(r)]
time = [[0] * c for _ in range(r)]
position = deque([])
dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]
# ์งํ์ด์ ์์น์ ๋ถ์ ์์น๋ฅผ ์ฐพ๋๋ค.
for i in range(r):
for j in range(c):
# ์งํ์ด ๋จผ์ ๋ฃ๊ธฐ
if maze[i][j] == 'J':
# 3. ๋ฐ๋ก ํ์ถ ๊ฐ๋ฅํ๋ฉด ํ์ถํ๊ธฐ
if not (1 <= i < r - 1 and 1 <= j < c - 1):
print(1)
exit(0)
position.appendleft((i, j))
elif maze[i][j] == 'F':
position.append((i, j))
# ํ์ถํ๋ฌ๊ฐ๊ธฐ
print(escape(position))