guwon2784   1년 전

시간을 줄이기 위해서 짧은 식견으로 갖갖은 노력을 들였지만 

여기서 더 시간을 줄이기 힘들어서 질문 드립니다... 

논리적으로 부족한 부분이나 필요없는 시행등이 일어나는 부분을 찾아주시면 감사할 것 같습니다. 도와주세요 ㅠㅜ

siyamaki   1년 전

매 반복문마다 bfs를 돌리면

0 1 0 1 ...

1 0 1 0 ...

...

같은 모양의 배열에서 1000 by 1000의 graph 배열을 계속 복사해 시간초과가 날 것 같네요. 

1인 부분을 모두 큐에 넣고 bfs를 한번만 돌리거나 graph를 global로 선언하면 될 것 같습니다

guwon2784   1년 전

말씀해주신 방법으로 해결했습니다!! 감사합니다 그런데 똑같이 이중 for문으로 1을 찾는 과정을 하는건데 시간이 더 빠른이유를 혹시 설명해주실 수 있을까요? 

(해결한 방법)

from collections import deque
import sys

input = sys.stdin.readline

def bfs(n, m):
    move_x = [-1, 0, 1, 0]
    move_y = [0, -1, 0, 1]
    while que:
        x, y = que.popleft()

        for i in range(4):
            dx = x + move_x[i]
            dy = y + move_y[i]
            if not 0 <= dx < n or not 0 <= dy < m or graph[dx][dy] == -1 or graph[dx][dy] == 1:
                continue

            else:
                if graph[dx][dy] != 0 and graph[x][y] + 1 < graph[dx][dy]:
                    graph[dx][dy] = graph[x][y] + 1
                    que.append((dx, dy))

                elif graph[dx][dy] == 0:
                    graph[dx][dy] = graph[x][y] + 1
                    que.append((dx,dy))

m, n = map(int, input().split())
graph = []
que = deque([])
for i in range(n):
    a = list(map(int, input().split()))
    graph.append(a)

for i in range(n):
    for j in range(m):
        if graph[i][j] == 1:
            que.append((i, j))

bfs(n, m)

max_num = 0

for i in graph:
    if 0 in i:
        print(-1)
        break
    else:
        max_num = max(max_num, max(i))
else:
    print(max_num - 1)

siyamaki   1년 전

41번째 줄에 if 0 in [ ... ]이 O(N)이고 45번째줄에 max([ ... ])도 O(N)입니다

댓글을 작성하려면 로그인해야 합니다.