파이썬 알고리즘 문제 풀이

[백준] G5. boj7569 토마토 / 분류 : bfs

gogi masidda 2024. 4. 1. 19:21

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

 

7569번: 토마토

첫 줄에는 상자의 크기를 나타내는 두 정수 M,N과 쌓아올려지는 상자의 수를 나타내는 H가 주어진다. M은 상자의 가로 칸의 수, N은 상자의 세로 칸의 수를 나타낸다. 단, 2 ≤ M ≤ 100, 2 ≤ N ≤ 100,

www.acmicpc.net

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

M, N, H = map(int,input().split())
tomatoes = [[] for i in range(H)]

for i in range(H):
    for j in range(N):
        tomatoes[i].append(list(map(int, input().split())))

dx = [-1, 1, 0, 0, 0, 0]
dy = [0, 0, -1, 1, 0, 0]
dz = [0, 0, 0, 0, -1, 1]
queue = deque()

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

def bfs():
    while queue:
        z, y, x = queue.popleft()
        for idx in range(6):
            nz = z + dz[idx]
            ny = y + dy[idx]
            nx = x + dx[idx]
            if 0 <= nx < M and 0 <= ny < N and 0 <= nz < H:
                if tomatoes[nz][ny][nx] == 0:
                    tomatoes[nz][ny][nx] = tomatoes[z][y][x] + 1
                    queue.append((nz, ny, nx))

bfs()

not_complete = False
count = 0
for i in range(H):
    for j in range(N):
        for k in range(M):
            if tomatoes[i][j][k] == 0:
                not_complete = True
            count = max(count, tomatoes[i][j][k])

if not_complete:
    print(-1)
else:
    print(count-1)

bfs로 tomatoes 배열의 원소를 탐색하면서 익지 않은 토마토가 있는 경우(값이 0인 경우)에 이동 전 원소의 값에 1씩 더하며 박스 안에 토마토를 다 익히려면 얼마나 걸리는지 표시했다.

728x90