結果

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

ソースコード

diff #

from collections import defaultdict
from collections import deque
#import itertools

def bfs(start, end):
    cnt = 0
    nows = deque([start])
    visited = [False for i in range(N)]
    while True:
        if len(nows) == 0:
            return -1
        cnt += 1
        for _ in range(len(nows)):
            now = nows.popleft()
            visited[now] = True
            for after in graph[now]:
                if after == end:
                    return cnt
                if not visited[after]:
                    nows.append(after)

N, M = map(int, input().split())
graph = defaultdict(list)
for _ in range(M):
    u, v = map(int, input().split())
    graph[u - 1].append(v - 1)
#for i in range(N):
#    print(str(i) + ": ", end = "")
#    print(*graph[i])

# route1: 0 -> N - 2 -> N - 1 -> 0
sec1 = bfs(0, N - 2)
sec2 = bfs(N - 2, N - 1)
sec3 = bfs(N - 1, 0)
route1 = sec1 + sec2 + sec3 if sec1 >= 0 and sec2 >= 0 and sec3 >= 0 else -1
# route2: 0 -> N - 1 -> N - 2 -> 0
sec1 = bfs(0, N - 1)
sec2 = bfs(N - 1, N - 2)
sec3 = bfs(N - 2, 0)
route2 = sec1 + sec2 + sec3 if sec1 >= 0 and sec2 >= 0 and sec3 >= 0 else -1
if route1 >= 0 and route2 >= 0:
    print(min(route1, route2))
elif route1 >= 0 and route2 < 0:
    print(route1)
elif route1 < 0 and route2 >= 0:
    print(route2)
else:
    print(-1)
0