結果

問題 No.2565 はじめてのおつかい
ユーザー noriaoki
提出日時 2023-12-02 16:34:36
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 380 ms / 2,000 ms
コード長 745 bytes
コンパイル時間 248 ms
コンパイル使用メモリ 82,048 KB
実行使用メモリ 116,096 KB
最終ジャッジ日時 2024-09-26 20:27:09
合計ジャッジ時間 14,275 ms
ジャッジサーバーID
(参考情報)
judge2 / judge1
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 50
権限があれば一括ダウンロードができます

ソースコード

diff #

N, M = map(int, input().split())
UV = [map(int, input().split()) for _ in range(M)]

graph = [[] for _ in range(N)]
for U, V in UV:
    U -= 1
    V -= 1
    graph[U].append(V)
import collections
def bfs(start, goal):
    q = collections.deque()
    q.append(start)
    reached = [0] * N
    while q:
        now = q.popleft()
        for g in graph[now]:
            if reached[g]:
                continue
            reached[g] = reached[now] + 1
            q.append(g)
    return reached[goal]

ans = 10**18
a = bfs(0, N-2)
b = bfs(N-2, N-1)
c = bfs(N-1, 0)
if a and b and c:
    ans = min(ans, a + b + c)
a = bfs(0, N-1)
b = bfs(N-1, N-2)
c = bfs(N-2, 0)
if a and b and c:
    ans = min(ans, a + b + c)

print(ans if ans != 10**18 else -1)
0