알고리즘 공부/백준

(Python)백준 코딩테스트 연습 - 토마토(7576)

HRuler 2023. 7. 15. 19:51

1. 문제

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

 

7576번: 토마토

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

www.acmicpc.net

2. 풀이

import sys
input = sys.stdin.readline
from collections import deque

# m, n : 상자의 가로, 세로 칸 수
m, n = map(int, input().split())

# boxL : box 정보를 담은 리스트
boxL = [list(map(int, input().split())) for i in range(n)]
q = deque()

for i in range(n):
    for j in range(m):
        if boxL[i][j] == 1:
            q.append([i, j])
cnt = 0
for i in range(n*m):
    cnt += 1
    new_q = deque()
    while q:
        x, y = map(int, q.popleft())
        if x - 1 >= 0 and boxL[x-1][y] == 0:
            boxL[x-1][y] = 1
            new_q.append([x-1, y])
        if y + 1 < m and boxL[x][y+1] == 0:
            boxL[x][y+1] = 1
            new_q.append([x, y+1])
        if x + 1 < n and boxL[x+1][y] == 0:
            boxL[x+1][y] = 1
            new_q.append([x+1, y])
        if y - 1 >= 0 and boxL[x][y-1] == 0:
            boxL[x][y-1] = 1
            new_q.append([x, y-1])
    if len(new_q) == 0:
        break
    q = new_q

isRipe = True
for i in boxL:
    for j in i:
        if j == 0:
            isRipe = False
            break
if isRipe:
    print(cnt-1)
else:
    print(-1)