백준 7576번 토마토

highway92·2021년 10월 1일
0

백준

목록 보기
14/27

문제출처 : https://www.acmicpc.net/problem/7576

풀이과정

1. 익은 토마토의 인덱스를 q에 저장

2. q를 popleft()하며 가능한 토마토 들을 모두 익혀나감

3. 큐가 비고나면 for문을 통해 탐색

import sys
from collections import deque
def solve():
    input = sys.stdin.readline

    x,y = list(map(int,input().split()))
    box=[]
    q=deque()
    for i in range(y):
        box.append(list(map(int,input().split())))

    for i in range(len(box)):
        for j in range(len(box[i])):
            if box[i][j] == 1:
                q.append([i,j])

    while q:
        a,b = q.popleft()
        direction=[1,-1]
        for i in direction:
            if 0<=a+i<y:
                if box[a+i][b] == 0:
                    box[a+i][b] = box[a][b] + 1
                    q.append([a+i,b])
            if 0<=b+i<x:
                if box[a][b+i] == 0:
                    box[a][b+i] = box[a][b] + 1
                    q.append([a,b+i])

    result = -999999
    for i in range(len(box)):
        for j in range(len(box[i])):
            if box[i][j] == 0:
                return print(-1)
            elif box[i][j] > result:
                result = box[i][j]

    return print(result-1)

solve()
profile
웹 개발자로 활동하고 있습니다.

0개의 댓글