개발/algorithm
[백준 7569번] 토마토 - python
zzi_on2
2022. 2. 17. 15:06
문제 링크
https://www.acmicpc.net/problem/7569
7569번: 토마토
첫 줄에는 상자의 크기를 나타내는 두 정수 M,N과 쌓아올려지는 상자의 수를 나타내는 H가 주어진다. M은 상자의 가로 칸의 수, N은 상자의 세로 칸의 수를 나타낸다. 단, 2 ≤ M ≤ 100, 2 ≤ N ≤ 100,
www.acmicpc.net
풀이
- 백준 7576번 토마토 문제를 3차원으로 확장시킨 것이다.
- 따라서 3차원 배열을 위, 아래, 왼쪽, 오른쪽, 앞, 뒤 여섯 방향에 대하여 bfs로 탐색해주면 된다.
from collections import deque
import sys
input = sys.stdin.readline
dh = [ 1, -1 , 0, 0 , 0, 0 ]
dx = [ 0 ,0, 1, -1, 0, 0 ]
dy = [ 0, 0, 0, 0, 1, -1 ]
def bfs():
while q:
x, y, z = q.popleft()
# 위, 아래, 왼쪽, 오른쪽, 앞, 뒤 여섯 방향에 대하여 탐색
for i in range(6):
nh = x + dh[i]
nx = y + dx[i]
ny = z + dy[i]
if 0<= nh < h and 0 <= nx < n and 0 <= ny < m and graph[nh][nx][ny] == 0:
graph[nh][nx][ny] = graph[x][y][z] + 1
q.append((nh, nx,ny))
m, n, h = map(int,input().split())
graph = []
for i in range(h):
tmp = []
for j in range(n):
tmp.append(list(map(int,input().split())))
graph.append(tmp)
q = deque()
# 토마토 위치 저장
for k in range(h):
for i in range(n):
for j in range(m):
if graph[k][i][j] == 1:
q.append((k,i,j))
bfs()
result = 0
for k in graph:
for i in k:
for j in i:
if j == 0:
print(-1)
exit(0)
result = max(result, j)
print(result-1)