4179 / 5427 - 동일 큐 다른 속성

nhwang·2022년 7월 8일
0

BFS_유형화

목록 보기
1/3
import sys
from collections import deque

n, m = map(int, sys.stdin.readline().strip().split())
origin = []
for _ in range(n):
    origin.append(list(map(str, sys.stdin.readline().strip())))
fire = []
for i in range(n):
    for j in range(m):
        if origin[i][j] == 'J':
            sy,sx = i, j
            origin[i][j] = 0
        elif origin[i][j] == 'F':
            fire.append((i, j))

answer = []

def bfs():
    q = deque()
    q.appendleft((sy,sx))
    while(fire):
        q.appendleft(fire.pop())
    while(q):
        y,x = q.pop()
        ny = [1,-1,0,0]
        nx = [0,0,-1,1]
        for v in range(4):
            dy = y+ny[v]
            dx = x+nx[v]
            if dy < 0 or dx < 0 or dy >= n or dx >=m:
                if origin[y][x] != 'F':
                    answer.append(origin[y][x]+1)
                continue
            if origin[y][x] == 'F':
                if origin[dy][dx] == 'F' or origin[dy][dx] == '#':
                    continue
                q.appendleft((dy,dx))
                origin[dy][dx] = 'F'
            else:
                if origin[dy][dx] != '.':
                    continue
                q.appendleft((dy,dx))
                origin[dy][dx] = origin[y][x] + 1

bfs()
if answer:
    print(min(answer))
else:
    print("IMPOSSIBLE")
  1. 큐에 넣을 거 우선순위 결정 (서로 영향을 줄 수 있음)
  2. 종결조건 꼼꼼히 확인 (bfs는 q가 끝날때까지 돌아야하는 경우가 많고, 이번 케이스는 아예 벡터가 밖일때를 값으로 모았어야했다.(바로 리턴도 안됌. 더 짧은게 있었을 수 있음)
profile
42Seoul

0개의 댓글