[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())



Categories:

Updated:

Leave a comment