알고리즘 공부

[BOJ] 토마토(7569) 문제 풀기 | Python3

유나쒸 2021. 4. 30. 19:34


유의사항 -  python3 언어로 실행 시키면 시간초과가 뜨니 PyPy3 언어로 실행시켜주세요. (아마도 컴파일러가 달라서 그런듯 합니다)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
from collections import deque
 
M, N, H=list(map(int, input().split()))
boxs=[[list(map(int, input().split())) for n in range(N)] for h in range(H)]
visit=[[[0]*for n in range(N)] for h in range(H)]
 
dx=[-1,1,0,0,0,0]
dy=[0,0,-1,1,0,0]
dz=[0,0,0,0,-1,1]
 
queue=deque()
for z in range(H):
    for y in range(N):
        for x in range(M):
            if boxs[z][y][x]==1:
                queue.append([z,y,x])
while queue:
    z,y,x=queue.popleft()
    visit[z][y][x]=1
 
    for i in range(6):
        nextx=x+dx[i]
        nexty=y+dy[i]
        nextz=z+dz[i]
        if 0<=nextx<and 0<=nexty<and 0<=nextz<H:
            if boxs[nextz][nexty][nextx]==0 and visit[nextz][nexty][nextx]==0:
                boxs[nextz][nexty][nextx]=boxs[z][y][x]+1
                visit[nextz][nexty][nextx]=1
                queue.append([nextz,nexty,nextx])
 
dayofall=-1
for box in boxs:
    for line in box:
        for dayoftomato in line:
            if dayoftomato==0:
                print(-1)
                exit(0)
            dayofall=max(dayofall, dayoftomato)
 
print(dayofall-1 if dayofall!=-1 else -1)
 
cs