[알고리즘/백준] 7576번 : 토마토(python)

유현민·2022년 3월 29일
0

알고리즘

목록 보기
82/253

익은 토마토 위치를 따로 저장한다. 저장할 때 위치 및 날짜를 0으로 설정해서 저장.
bfs를 돌리면서 주변에 익은 토마토들을 하나씩 큐에 저장. 저장하면서 day+1을 해준다.

from collections import deque


def solution():
    global ans
    q = deque(tomato)
    while q:
        x, y, day = q.popleft()
        if day > ans:
            ans = day
        for i in range(4):
            nx = x + dx[i]
            ny = y + dy[i]
            if 0 <= nx < N and 0 <= ny < M:
                if field[nx][ny] == 0:
                    field[nx][ny] = 1
                    q.append((nx, ny, day + 1))


if __name__ == "__main__":
    M, N = map(int, input().split())
    field = [list(map(int, input().split())) for _ in range(N)]
    tomato = list()
    ans = 0
    dx = [1, -1, 0, 0]
    dy = [0, 0, 1, -1]
    for i in range(N):
        for j in range(M):
            if field[i][j] == 1:
                tomato.append((i, j, 0))
    solution()
    for i in range(N):
        for j in range(M):
            if field[i][j] == 0:
                print(-1)
                exit(0)
    print(ans)
profile
smilegate megaport infra

0개의 댓글