본문 바로가기

알고리즘

[백준] 7576. 토마토 (Python)

-문제링크

www.acmicpc.net/problem/7576

 

7576번: 토마토

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

www.acmicpc.net

-풀이

from collections import deque
dx = [-1, 1, 0, 0]
dy = [0, 0, 1, -1]

m, n = map(int, input().split())
maps = [list(map(int,input().split())) for _ in range(n)]

q = deque()

for i in range(n):
    for j in range(m):
        if maps[i][j] == 1:
            q.append([i,j])


while q:
    x, y = q.popleft()
    for i in range(4):
        nx = x+dx[i]
        ny = y+dy[i]
        if 0<= nx <n and 0<= ny <m and maps[nx][ny] == 0:
            maps[nx][ny] = maps[x][y] + 1
            q.append([nx,ny])

for i in range(n):
    if 0 in maps[i] :
        print(-1)
        break
else :
    print(max(max(maps))-1)