[BaekJoon] ๋ฐฑ์ค 5427๋ฒ : ๋ถ
Updated:
5427๋ฒ : ๋ถ
์ผ๋ฐ์ ์ธ BFS ๋ฌธ์ ์ด์ง๋ง ๋ถ์ ๋จผ์ ํผ์ง๊ฒ ํ ๋ค ์๊ทผ์ด๋ฅผ ์ด๋์์ผ์ผํ๋ค.
import sys
from collections import deque
def fire():
# 1. ๋ฐฐ์ด๊ณผ ๋ฐฉ๋ฌธ์ฌ๋ถ, ์ด๋๋ฐฉํฅ ์ด๊ธฐํํ๋ค.
col, row = map(int, sys.stdin.readline().rsplit())
maps = [list(sys.stdin.readline()) for _ in range(row)]
dirs = [[-1, 0], [0, 1], [1, 0], [0, -1]]
visit = [[False for _ in range(col)] for _ in range(row)]
queue = deque([])
# 2. ๋ถ์ ์์น์ ์๊ทผ์ด ์์น๋ฅผ ์ ์ฅํ๋ค.
fires = []
start = []
for i in range(row):
for j in range(col):
if maps[i][j] == '@':
start = [i, j, '@', 0]
elif maps[i][j] == '*':
fires.append([i, j, '*', 0])
visit[start[0]][start[1]] = True
# 3. ๋ถ์ด ๋จผ์ ํผ์ ธ์ผํ๊ธฐ ๋๋ฌธ์ ํ์ ๋ถ์ ์์น๋ฅผ ๋จผ์ ๋ฃ๋๋ค.
for value in fires:
queue.append(value)
visit[value[0]][value[1]] = True
queue.append(start)
# 4. BFS๋ฅผ ์์ํ๋ค.
while queue:
now_i, now_j, state, time = queue.popleft()
# 5. ์๊ทผ์ด๊ฐ ๋งต ๊ฐ์ฅ์๋ฆฌ์ ์๋๊ฒฝ์ฐ ํ์ถ ํ ์ ์๋ค.
if state == '@' and (now_i == 0 or now_j == 0 or now_i == row - 1 or now_j == col - 1):
return time + 1
for value in dirs:
visit_i, visit_j = now_i + value[0], now_j + value[1]
if 0 <= visit_i < row and 0 <= visit_j < col and not visit[visit_i][visit_j]:
# 6. ๋ถ์ธ๊ฒฝ์ฐ ํผ์ง๋ฉด์ ํผ์ง๋ ์์น๋ฅผ ๋ถ๋ก ๋ฐ๊ฟ์ค๋ค.
if maps[visit_i][visit_j] != '#' and state == '*':
maps[visit_i][visit_j] = '*'
visit[visit_i][visit_j] = True
queue.append([visit_i, visit_j, '*', time + 1])
# 7. ์๊ทผ์ด๋ ๊ฐ์ ์์ ๊ธฐ์ค ์ด๋ฏธ ๋ถ์ด ํผ์ก๊ธฐ ๋๋ฌธ์ ์ด๋๋ง ํ๋ฉด ๋๋ค.
elif maps[visit_i][visit_j] == '.' and state == '@':
visit[visit_i][visit_j] = True
queue.append([visit_i, visit_j, '@', time + 1])
return "IMPOSSIBLE"
if __name__ == "__main__":
for _ in range(int(input())):
print(fire())
Leave a comment