백준 7576 토마토

김민영·2022년 12월 28일
0

알고리즘

목록 보기
9/125

토마토

풀이 계획

  • BFS
  • 전체 리스트 순회하며 최외각 토마토만 큐에 저장
  • 날짜++ 하며 list의 값 변경
import sys
from collections import deque
input = sys.stdin.readline

M, N = map(int, input().split())
map_lst = []
queue = deque([])
for i in range(N):
    map_lst.append(list(map(int, input().split())))
    for j in range(M):
        if map_lst[i][j] == 1:
            queue.append([j, i, 0])

# 상 우 하 좌
dx = [0, 1, 0, -1]
dy = [1, 0, -1, 0]


def bfs():
    days = 0
    while queue:
        v = queue.popleft()
        x = v[0]
        y = v[1]
        days = v[2]
        for idx in range(4):
            nx = x + dx[idx]
            ny = y + dy[idx]
            if nx < 0 or ny < 0 or nx >= M or ny >= N or map_lst[ny][nx] != 0:
                continue
            map_lst[ny][nx] = 1
            queue.append([nx, ny, days + 1])
        if queue:
            days = queue[-1][2]
    for ix in range(N):
        if 0 in map_lst[ix]:
            return -1
    return days


print(bfs())
  • days를 while 전에 초기화 안해서 에러가 생김. UnboundLocalError, NameError
  • 그리고 days 리턴을 이상한데서 해서 틀림
profile
노션에 1차 정리합니당 - https://cream-efraasia-f3c.notion.site/4fb02c0dc82e48358e67c61b7ce8ab36?v=

0개의 댓글