結果

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

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 46 ms
54,656 KB
testcase_01 AC 45 ms
54,528 KB
testcase_02 AC 44 ms
54,912 KB
testcase_03 AC 45 ms
54,656 KB
testcase_04 AC 43 ms
54,400 KB
testcase_05 AC 44 ms
54,528 KB
testcase_06 AC 46 ms
54,912 KB
testcase_07 AC 45 ms
54,912 KB
testcase_08 AC 45 ms
54,528 KB
testcase_09 AC 45 ms
55,168 KB
testcase_10 AC 207 ms
90,752 KB
testcase_11 AC 369 ms
121,936 KB
testcase_12 AC 361 ms
96,824 KB
testcase_13 AC 176 ms
87,480 KB
testcase_14 AC 450 ms
112,804 KB
testcase_15 AC 652 ms
149,872 KB
testcase_16 AC 490 ms
128,640 KB
testcase_17 AC 643 ms
150,360 KB
testcase_18 AC 641 ms
149,992 KB
testcase_19 AC 661 ms
151,292 KB
testcase_20 AC 319 ms
163,760 KB
testcase_21 AC 331 ms
165,300 KB
testcase_22 AC 320 ms
163,764 KB
testcase_23 AC 324 ms
164,280 KB
testcase_24 AC 326 ms
164,664 KB
testcase_25 AC 366 ms
165,912 KB
testcase_26 AC 358 ms
166,284 KB
testcase_27 AC 359 ms
166,392 KB
testcase_28 AC 356 ms
164,276 KB
testcase_29 AC 356 ms
165,900 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