結果

問題 No.2565 はじめてのおつかい
ユーザー ntuda
提出日時 2023-12-04 20:22:38
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 293 ms / 2,000 ms
コード長 679 bytes
コンパイル時間 232 ms
コンパイル使用メモリ 82,176 KB
実行使用メモリ 100,864 KB
最終ジャッジ日時 2024-09-26 23:11:54
合計ジャッジ時間 10,985 ms
ジャッジサーバーID
(参考情報)
judge4 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 50
権限があれば一括ダウンロードができます

ソースコード

diff #

N, M = map(int, input().split())
UV = [list(map(int, input().split())) for _ in range(M)]
E = [[] for _ in range(N + 1)]
for u, v in UV:
    E[u].append(v)

INF = 10 ** 6
def bfs(a, b):
    nv = [True] * (N + 1)
    q = [a]
    cnt = 0
    while q:
        q2 = []
        while q:
            x = q.pop(-1)
            if x == b:
                return cnt
            for y in E[x]:
                if nv[y]:
                    nv[y] = False
                    q2.append(y)
        cnt += 1
        q, q2 = q2, q
    return INF

ans = min(bfs(1, N - 1) + bfs(N - 1, N) + bfs(N, 1), bfs(1, N) + bfs(N, N - 1) + bfs(N - 1, 1))
if ans >= INF:
    print(-1)
else:
    print(ans)
0