백준 7576 - 토마토 (파이썬)

Updated:

Answer

from sys import stdin
from collections import deque

input = stdin.readline

def bfs():
    global count, queue

    while queue:
        x, y = queue.popleft()

        for dx, dy in (0, 1), (0, -1), (1, 0), (-1, 0):
            nx = x + dx
            ny = y + dy

            if nx < 0 or nx >= N or ny < 0 or ny >= M:
                continue

            if matrix[nx][ny] == 0:
                queue.append((nx, ny))
                matrix[nx][ny] = matrix[x][y] + 1

M, N = map(int, input().split())
matrix = [list(map(int, input().split())) for _ in range(N)]
queue = deque([])

for i in range(N):
    for j in range(M):
        if matrix[i][j] == 1:
            queue.append((i, j))

bfs()
answer = 0

for i in matrix:
    for j in i:
        if j == 0:
            print(-1)
            exit(0)
            
    answer = max(answer, max(i))

print(answer - 1)

Categories:

Updated: