結果

問題 No.1565 Union
ユーザー ThetaTheta
提出日時 2024-04-16 11:54:45
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 707 ms / 2,000 ms
コード長 988 bytes
コンパイル時間 266 ms
コンパイル使用メモリ 82,292 KB
実行使用メモリ 166,284 KB
最終ジャッジ日時 2024-04-16 11:54:56
合計ジャッジ時間 11,272 ms
ジャッジサーバーID
(参考情報)
judge3 / judge5
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 48 ms
54,656 KB
testcase_01 AC 48 ms
54,400 KB
testcase_02 AC 50 ms
54,400 KB
testcase_03 AC 48 ms
54,784 KB
testcase_04 AC 48 ms
54,400 KB
testcase_05 AC 48 ms
54,272 KB
testcase_06 AC 49 ms
54,528 KB
testcase_07 AC 50 ms
55,168 KB
testcase_08 AC 48 ms
54,400 KB
testcase_09 AC 50 ms
54,656 KB
testcase_10 AC 228 ms
90,848 KB
testcase_11 AC 392 ms
122,060 KB
testcase_12 AC 410 ms
96,584 KB
testcase_13 AC 187 ms
87,588 KB
testcase_14 AC 473 ms
113,052 KB
testcase_15 AC 704 ms
150,328 KB
testcase_16 AC 503 ms
128,972 KB
testcase_17 AC 698 ms
149,744 KB
testcase_18 AC 665 ms
149,996 KB
testcase_19 AC 707 ms
150,776 KB
testcase_20 AC 336 ms
164,000 KB
testcase_21 AC 353 ms
165,244 KB
testcase_22 AC 343 ms
163,816 KB
testcase_23 AC 348 ms
164,196 KB
testcase_24 AC 349 ms
164,284 KB
testcase_25 AC 387 ms
165,864 KB
testcase_26 AC 384 ms
165,968 KB
testcase_27 AC 378 ms
166,124 KB
testcase_28 AC 387 ms
164,292 KB
testcase_29 AC 371 ms
166,284 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

from collections import deque
from heapq import heappop
from math import inf, isinf


def bfs_dist(graph: list[set[int]], start: int, goal: int) -> int | float:
    distance = [inf for _ in graph]
    distance[start] = 0
    queue = deque([start])
    visited = set()
    while queue:
        current = queue.popleft()
        visited.add(current)
        for dest in graph[current]:
            if dest in visited:
                continue
            if distance[dest] <= distance[current] + 1:
                continue
            queue.append(dest)
            distance[dest] = distance[current] + 1

    return distance[goal]


def main():
    N, M = map(int, input().split())
    graph = [set() for _ in range(N)]
    for _ in range(M):
        a, b = map(int, input().split())
        graph[a - 1].add(b - 1)
        graph[b - 1].add(a - 1)

    if isinf((dist := bfs_dist(graph, 0, N - 1))):
        print(-1)
    else:
        print(dist)


if __name__ == "__main__":
    main()
0