백준 7569 토마토

김민영·2022년 12월 28일
0

알고리즘

목록 보기
10/125

토마토

계획

  • 3차원 BFS
  • 입력 주의해서 받기
  • 이전 토마토 문제랑 똑같이 풀어야지
  • BFS 모두 한 후에 마지막에 0 있으면 -1 출력하기
import sys
from collections import deque

input = sys.stdin.readline

M, N, H = map(int, input().split())
map_lst = []
queue = deque([])
for h in range(H):
    add_lst = []
    for _ in range(N):
        add_lst.append(list(map(int, input().split())))
    map_lst.append(add_lst)
for h in range(H):
    for n in range(N):
        for m in range(M):
            if map_lst[h][n][m] == 1:
                queue.append([m, n, h, 0])

# 북 동 남 서 상 하
dx = [0, 1, 0, -1, 0, 0]
dy = [1, 0, -1, 0, 0, 0]
dz = [0, 0, 0, 0, 1, -1]


def bfs():
    days = 0
    while queue:
        v = queue.popleft()
        x = v[0]
        y = v[1]
        z = v[2]
        days = v[3]
        for i in range(6):
            nx = x + dx[i]
            ny = y + dy[i]
            nz = z + dz[i]
            if nx < 0 or ny < 0 or nz < 0 or nx >= M or ny >= N or nz >= H or map_lst[nz][ny][nx] != 0:
                # print(nx, M, ny, N, nz, H)
                continue
            map_lst[nz][ny][nx] = 1
            queue.append([nx, ny, nz, days+1])
            # print(queue)
    for h in range(H):
        for n in range(N):
            for m in range(M):
                if map_lst[h][n][m] == 0:
                    return -1
    return days


print(bfs())
  • 2차원 토마토 풀 때랑 똑같이 풀었다.
  • 자꾸 bfs 구현할 때 큐에 넣어주는 것을 깜박한다...
profile
노션에 1차 정리합니당 - https://cream-efraasia-f3c.notion.site/4fb02c0dc82e48358e67c61b7ce8ab36?v=

0개의 댓글