[백준/Python] 7596 토마토

2.so_j·2023년 8월 3일

문제는 여기

코드

import sys
from collections import deque
input = sys.stdin.readline
m,n,h = map(int, input().split())
graph = [[list(map(int, input().split())) for _ in range(n)] for _ in range(h)]
queue = deque()

dx = [-1,1,0,0,0,0]
dy = [0,0,-1,1,0,0]
dz = [0,0,0,0,-1,1]


cnt = 0
for z in range(h):
    for y in range(n):
        for x in range(m):
            if graph[z][y][x] == 1:
                queue.append((x,y,z,0))
            elif graph[z][y][x] == 0:
                cnt += 1

if cnt == 0:
    print(0)
else:
    result = 0

    while queue:
        x, y, z, cnt = queue.popleft() 
        result = cnt

        for i in range(6):
            nx = dx[i] + x
            ny = dy[i] + y
            nz = dz[i] + z

            if 0 <= nx < m and 0 <= ny < n and 0 <= nz < h and not graph[nz][ny][nx]: 
                if graph[nz][ny][nx] == -1:
                    continue
                graph[nz][ny][nx] = 1
                queue.append((nx, ny, nz, cnt + 1))

    for z in range(h):
        for y in range(n):
            for x in range(m):
                if graph[z][y][x] == 0:
                    print(-1)
                    exit()

    print(result)

기록할 점

  • 처음엔 토마토의 위치를 2차원 배열에 담았었다. 분명 주어진 테스트 케이스는 전부 맞았는데 제출하면 틀렸다고 함
  • 질문 게시판에서 찾은 테스트 케이스인데, 2차원 배열로 진행하게 되면 이런 경우에도 토마토를 익게 해버린다. (-1이 출력 되어야함)
  • 결론 : 토마토의 위치를 3차원 배열에 넣어주어야함. 나머지는 7576 토마토와 유사하다

profile
싱글코어 두뇌의 개발자 도전기

0개의 댓글