반응형
처음에 python으로 제출했더니 채점되다가 시간 에러가 뜸 그래서 pypy(반복문이 많을 경우 계산이 빠르다고 함)로 제출했더니 맞았다!!
토마토 문제는 bfs를 이용해서 풀었고 층 수별로 박스가 나눠진 3차원 구조여서 dict를 이용해서 3차원 배열을 저장했다!
queue에는 현재 1인 값들 즉 익은 토마토가 있는 것들의 row,col,height을 저장했고
temp에는 queue에 있는 1인 값들의 토마토 주변에 값이 0이어서 하루가 지나면 1이 되는 것들을 넣어서 다시 queue에 넣어줬다,
temp에 아무것도 없는 경우 => 익을게 없는 경우 while문 탈출하도록 했다.
import sys
from collections import deque
input = sys.stdin.readline
m,n,h = map(int,input().split())
graph={}
for i in range(h):
ary=[list(map(int,input().split())) for _ in range(n)]
graph[i]=ary
queue=deque()
for height in range(h):
for row in range(n):
for col in range(m):
if graph[height][row][col]==1:
queue.append([row,col,height])
dh=[1,-1,0,0,0,0]
dx=[0,0,-1,1,0,0]
dy=[0,0,0,0,1,-1]
days=0
while True:
temp=[]
while queue:
tomato = queue.popleft()
for i in range(6):
height = dh[i] + tomato[2]
row = dx[i] + tomato[0]
col = dy[i] + tomato[1]
if 0<=height<h and 0<=row<n and 0<=col<m and graph[height][row][col] == 0:
graph[height][row][col]=1
temp.append([row,col,height])
if temp:
days+=1
queue+=temp
else:
break
finished=True
for height in range(h):
for row in range(n):
for col in range(m):
if graph[height][row][col]==0:
finished=False
if finished:
print(days)
else:
print(-1)
반응형
'Algorithm > Baekjoon' 카테고리의 다른 글
5014번 파이썬 (0) | 2022.03.21 |
---|---|
1697번 파이썬 (0) | 2022.03.20 |
2644번 파이썬 (0) | 2022.03.20 |
10844번 파이썬 (0) | 2022.03.17 |
2667번 파이썬 (0) | 2022.03.17 |