알고리즘/백준
[백준`G5] 7569 - 토마토 (Python)
셰욘
2024. 3. 14. 01:04
728x90
문제 설명
https://www.acmicpc.net/problem/7569
7569번: 토마토
첫 줄에는 상자의 크기를 나타내는 두 정수 M,N과 쌓아올려지는 상자의 수를 나타내는 H가 주어진다. M은 상자의 가로 칸의 수, N은 상자의 세로 칸의 수를 나타낸다. 단, 2 ≤ M ≤ 100, 2 ≤ N ≤ 100,
www.acmicpc.net
문제 풀이
높이까지 있는 BFS문제다.
dx, dy, dh로 각각 이동하는 범위를 설정하고
queue를 돌면서 확인해줬다-!
from collections import deque
M, N, H = list(map(int, input().split()))
tomato = [[list(map(int, input().split())) for _ in range(N)] for __ in range(H)]
dx = [0, 0, 1, -1, 0, 0]
dy = [0, 0, 0, 0, 1, -1]
dh = [1, -1, 0, 0, 0, 0]
result = 0
def bfs():
while queue:
x, y, h = queue.popleft()
for i in range(6):
nx = x + dx[i]
ny = y + dy[i]
nh = h + dh[i]
if 0 <= nx < M and 0 <= ny < N and 0 <= nh < H:
if tomato[nh][ny][nx] == 0:
queue.append((nx, ny, nh))
tomato[nh][ny][nx] = tomato[h][y][x] + 1
return
queue = deque()
for i in range(H):
for j in range(N):
for k in range(M):
if tomato[i][j][k] == 1:
queue.append((k, j, i))
bfs()
for i in range(H):
for j in range(N):
if 0 in tomato[i][j]:
print(-1)
exit(0)
result = max(max(tomato[i][j]), result)
print(result - 1)
728x90