https://www.acmicpc.net/problem/7569
시간초과 뜬 내 코드
import sys
from collections import deque
input = sys.stdin.readline
m, n, h = map(int, input().split())
graph = []
for _ in range(n * h):
graph.append(list(map(int, input().split())))
dx = [0, 0, -1, 1, -n, n]
dy = [1, -1, 0, 0, 0, 0]
def bfs(i, j):
q = deque()
q.append((i, j))
while q:
tempx, tempy = q.popleft()
for idx in range(6):
x = tempx + dx[idx]
y = tempy + dy[idx]
if 0 <= x < n * h and 0 <= y < m and ((graph[x][y] >= 1 and graph[x][y] > graph[tempx][tempy] + 1) or graph[x][y] == 0):
q.append((x, y))
graph[x][y] = graph[tempx][tempy] + 1
#이중배열에서 원소 찾기
if all(0 not in l for l in graph):
print(0)
else:
for i in range(n * h):
for j in range(m):
if graph[i][j] == 1:
bfs(i, j)
if any(0 in ele for ele in graph):
print(-1)
else:
maxval = 0
for el in graph:
maxval = max(maxval, max(el))
print(maxval - 1)
이 코드 짜면서 출력할 값을 분화했는데
if all(0 not in l for l in graph):
if any(0 in i for i in graph):
이런 표현 찾았는데
이렇게 짜지 않아도 더 효율적으로 짤 수 있었다..!
시간 초과도.. bfs 함수를 for 문 안에 넣으면서 더 돌아갔나..?
멋쟁이 스터디원!!!
스터디원 코드
from sys import stdin
from collections import deque
dx = [1, -1, 0, 0, 0, 0]
dy = [0, 0, 1, -1, 0, 0]
dz = [0, 0, 0, 0, 1, -1]
queue = deque([])
def bfs():
while queue:
x, y, z = queue.popleft()
for i in range(6):
nx = x + dx[i]
ny = y + dy[i]
nz = z + dz[i]
if 0 <= nx < h and 0 <= ny < n and 0 <= nz < m and not graph[nx][ny][nz]:
graph[nx][ny][nz] = graph[x][y][z] + 1
queue.append([nx, ny, nz])
m, n, h = map(int, stdin.readline().split())
graph = [[list(map(int, stdin.readline().split())) for _ in range(n)] for _ in range(h)]
for i in range(h):
for j in range(n):
for k in range(m):
if graph[i][j][k] == 1:
queue.append([i, j, k])
bfs()
answer = 0
for i in graph:
for j in i:
if 0 in j:
print(-1)
exit(0)
answer = max(answer, max(j))
print(answer - 1)