PS/Python

[백준] 7576 - 토마토 (파이썬, Python)

w00se 2020. 7. 29. 00:55

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

 

7576번: 토마토

첫 줄에는 상자의 크기를 나타내는 두 정수 M,N이 주어진다. M은 상자의 가로 칸의 수, N은 상자의 세로 칸의 수를 나타낸다. 단, 2 ≤ M,N ≤ 1,000 이다. 둘째 줄부터는 하나의 상자에 저장된 토마토�

www.acmicpc.net

from collections import deque
import sys

def solution(start_list):
    queue = deque(start_list)
    cnt = len(queue)
    flag = 0
    day = -1

    drow = [0, 1, 0, -1]
    dcol = [-1, 0, 1, 0]

    while queue:
        flag += 1
        pos = queue.popleft()

        for k in range(4):
            crow = pos[0]+drow[k]
            ccol = pos[1]+dcol[k]

            if(0 <= crow and crow < N and 0 <= ccol and ccol < M):
                if(matrix[crow][ccol] == 0):
                    matrix[crow][ccol] = 1
                    queue.append((crow, ccol))                

        if(flag == cnt):
            flag = 0
            cnt = len(queue)
            day += 1

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



M, N = map(int, sys.stdin.readline().rstrip().split())

matrix = [list(map(int, sys.stdin.readline().rstrip().split())) for _ in range(N)]

start = []

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

print(solution(start))