7569번: 토마토
첫 줄에는 상자의 크기를 나타내는 두 정수 M,N과 쌓아올려지는 상자의 수를 나타내는 H가 주어진다. M은 상자의 가로 칸의 수, N은 상자의 세로 칸의 수를 나타낸다. 단, 2 ≤ M ≤ 100, 2 ≤ N ≤ 100,
www.acmicpc.net
앞에서 풀었던 토마토 문제와 같은 방법으로 BFS를 사용해서 풀면 쉽게 풀 수 있었다. 대신 2차원이 아닌 3차원 배열이라서 H의 값을 더 추가해서 풀었다. 코드는 앞에서 풀었던 BFS와 똑같지만 matrix의 차원만 하나 더 추가된 방법으로 풀었다. 그래서 쉽게 풀 수 있었다.
import sys
from collections import deque
input = sys.stdin.readline
directions = [(1, 0, 0), (-1, 0, 0), (0, -1, 0),(0, 0, -1),(0, 1, 0),(0, 0, 1)]
def bfs(startPoints):
q = deque()
for p in startPoints:
q.append(p)
visited[p[0]][p[1]][p[2]] = True
while q:
start = q.popleft()
for d in directions:
nextZ = start[0] + d[0]
nextX = start[1] + d[1]
nextY = start[2] + d[2]
if (0<=nextZ<h and 0<=nextX<n and 0<=nextY<m) and matrix[nextZ][nextX][nextY] == 0:
q.append((nextZ, nextX, nextY))
matrix[nextZ][nextX][nextY] = matrix[start[0]][start[1]][start[2]] + 1
visited[nextZ][nextX][nextY] = True
m, n, h = map(int, input().split())
visited = [[[False]*m for _ in range(n)] for _ in range(h)]
matrix = [[list(map(int, input().split())) for _ in range(n)] for _ in range(h)]
multiSource = [(k, i, j) for k in range(h) for i in range(n) for j in range(m) if not visited[k][i][j] and matrix[k][i][j] == 1]
bfs(multiSource)
result = 0
for i in matrix:
for j in i:
if 0 in j:
print(-1)
exit(0)
result = max(max(j), result)
print(result-1)
'PS > 백준' 카테고리의 다른 글
실버3 1로 만들기(1463) (0) | 2023.12.30 |
---|---|
골드5 뱀과 사다리 게임(16928) (1) | 2023.12.28 |
골드5 토마토(7576) (1) | 2023.12.26 |
실버1 나이트의 이동(7562) (1) | 2023.12.22 |
실버2 유기농 배추(1012) (1) | 2023.12.21 |