結果

問題 No.1565 Union
ユーザー Theta
提出日時 2024-04-16 11:54:45
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 628 ms / 2,000 ms
コード長 988 bytes
コンパイル時間 432 ms
コンパイル使用メモリ 82,176 KB
実行使用メモリ 166,272 KB
最終ジャッジ日時 2024-12-20 18:58:36
合計ジャッジ時間 10,521 ms
ジャッジサーバーID
(参考情報)
judge5 / judge3
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 27
権限があれば一括ダウンロードができます

ソースコード

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