[백준/파이썬] 5427번

민정·2024년 1월 15일
0

[백준/파이썬]

목록 보기
235/245
post-thumbnail

📍백준 5427 문제

https://www.acmicpc.net/problem/5427!

코드

import sys
from collections import deque
input = sys.stdin.readline
dx = [0, 0, -1, 1]
dy = [1, -1, 0, 0]


def bfs():
    while que:
        x, y, s = que.popleft()
        for i in range(4):
            nx = x + dx[i]
            ny = y + dy[i]
            if 0 <= nx < n and 0 <= ny < m:
                if visited[nx][ny] == 0 and maps[nx][ny] == '.':
                    visited[nx][ny] = visited[x][y] + 1
                    que.append((nx, ny, s))
            else:
                if s == '@':
                    return visited[x][y]+1


testCase = int(input())


for _ in range(testCase):
    m, n = map(int, input().split())
    maps = []
    que = deque()
    visited = [[0 for _ in range(m)]for _ in range(n)]
    for _ in range(n):
        maps.append(list(input().rstrip('\n')))
    for i in range(n):
        for j in range(m):
            if maps[i][j] == '@':
                que.append((i, j, '@'))
            elif maps[i][j] == '*':
                que.appendleft((i, j, '*'))
    ans = bfs()
    if ans:
        print(ans)
    else:
        print("IMPOSSIBLE")
profile
パㅔバ6ㅇr 덤벼ㄹΓ :-0

0개의 댓글