BOJ - 7576 - 토마토

Updated:

import sys

def solution():
    M, N = map(int, sys.stdin.readline().split(' '))
    tomato = []
    Queue = []
    ret = 0

    for _ in range(N):
        tomato.append(list(map(int, sys.stdin.readline().split(' '))))

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

    while Queue:
        tempQueue = []

        for item in Queue:
            row, column = item[0], item[1]

            if column < M - 1 and tomato[row][column + 1] == 0:
                tomato[row][column + 1] = 1
                tempQueue.append((row, column + 1))

            if column > 0 and tomato[row][column - 1] == 0:
                tomato[row][column - 1] = 1
                tempQueue.append((row, column - 1))

            if row < N - 1 and tomato[row + 1][column] == 0:
                tomato[row + 1][column] = 1
                tempQueue.append((row + 1, column))

            if row > 0 and tomato[row - 1][column] == 0:
                tomato[row - 1][column] = 1
                tempQueue.append((row - 1, column))

        Queue = tempQueue
        ret += 1

    for i in range(N):
        for j in range(M):
            if tomato[i][j] == 0:
                print(-1)
                return

    print(ret-1)

solution()

https://www.acmicpc.net/problem/7576

Categories:

Updated:

Leave a comment