[백준] 7576번 토마토

거북이·2023년 2월 10일
0

백준[골드5]

목록 보기
1/82
post-thumbnail

💡문제접근

  • 문제를 잘못 읽어서 가로, 세로의 값을 받아오는 과정에서 IndexError를 계속 범했다.
    (문제 좀 잘 읽자..)

💡코드(메모리 : 98536KB, 시간 : 1468ms)

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

M, N = map(int, input().strip().split())
tomato = [list(map(int, input().strip().split())) for _ in range(N)]
queue = deque()
day = 0

def BFS():
    while queue:
        x, y = queue.popleft()
        dx = [0, 1, 0, -1]
        dy = [-1, 0, 1, 0]
        for i in range(4):
            nx = x + dx[i]
            ny = y + dy[i]
            if 0 <= nx < N and 0 <= ny < M and tomato[nx][ny] == 0:
                queue.append((nx, ny))
                tomato[nx][ny] = tomato[x][y] + 1
    return tomato

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

BFS()
for i in tomato:
    for j in i:
    	# 만약 행의 값이 전부 0이라면?
        # 조건문은 좌표의 값이 행렬의 범위 내에 있어야 하며 해당 좌표의 값이 0, 즉, 익지 않은 토마토의 경우에만 실행이 된다. 한 행의 값이 전부 다 0이라면 토마토가 모두 익지 못한 상황이므로 -1을 출력한다.
        if j == 0:
            print(-1)
            sys.exit(0)
    day = max(day, max(i))
print(day-1)

💡소요시간 : 40m

0개의 댓글