結果

問題 No.2565 はじめてのおつかい
ユーザー loop0919loop0919
提出日時 2023-11-03 15:52:18
言語 Python3
(3.12.2 + numpy 1.26.4 + scipy 1.12.0)
結果
AC  
実行時間 454 ms / 2,000 ms
コード長 886 bytes
コンパイル時間 115 ms
コンパイル使用メモリ 12,072 KB
実行使用メモリ 24,256 KB
最終ジャッジ日時 2023-11-03 15:52:35
合計ジャッジ時間 13,776 ms
ジャッジサーバーID
(参考情報)
judge13 / judge11
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 26 ms
10,184 KB
testcase_01 AC 24 ms
10,184 KB
testcase_02 AC 23 ms
10,184 KB
testcase_03 AC 454 ms
24,240 KB
testcase_04 AC 364 ms
24,256 KB
testcase_05 AC 24 ms
10,184 KB
testcase_06 AC 249 ms
15,396 KB
testcase_07 AC 141 ms
12,952 KB
testcase_08 AC 153 ms
13,356 KB
testcase_09 AC 235 ms
14,888 KB
testcase_10 AC 160 ms
13,884 KB
testcase_11 AC 352 ms
19,656 KB
testcase_12 AC 112 ms
11,784 KB
testcase_13 AC 176 ms
13,600 KB
testcase_14 AC 272 ms
16,816 KB
testcase_15 AC 267 ms
16,336 KB
testcase_16 AC 261 ms
21,560 KB
testcase_17 AC 75 ms
12,028 KB
testcase_18 AC 90 ms
14,420 KB
testcase_19 AC 352 ms
18,700 KB
testcase_20 AC 296 ms
17,884 KB
testcase_21 AC 273 ms
17,956 KB
testcase_22 AC 163 ms
15,124 KB
testcase_23 AC 196 ms
15,256 KB
testcase_24 AC 54 ms
11,204 KB
testcase_25 AC 318 ms
18,072 KB
testcase_26 AC 181 ms
14,708 KB
testcase_27 AC 259 ms
18,220 KB
testcase_28 AC 299 ms
18,500 KB
testcase_29 AC 343 ms
20,428 KB
testcase_30 AC 275 ms
19,148 KB
testcase_31 AC 299 ms
18,336 KB
testcase_32 AC 180 ms
14,888 KB
testcase_33 AC 333 ms
18,632 KB
testcase_34 AC 292 ms
17,436 KB
testcase_35 AC 277 ms
20,316 KB
testcase_36 AC 311 ms
18,668 KB
testcase_37 AC 184 ms
15,164 KB
testcase_38 AC 305 ms
17,548 KB
testcase_39 AC 241 ms
16,116 KB
testcase_40 AC 334 ms
20,320 KB
testcase_41 AC 360 ms
20,996 KB
testcase_42 AC 179 ms
14,744 KB
testcase_43 AC 269 ms
16,960 KB
testcase_44 AC 157 ms
13,524 KB
testcase_45 AC 85 ms
12,248 KB
testcase_46 AC 270 ms
16,880 KB
testcase_47 AC 228 ms
14,096 KB
testcase_48 AC 168 ms
13,764 KB
testcase_49 AC 112 ms
11,740 KB
testcase_50 AC 262 ms
14,556 KB
testcase_51 AC 24 ms
10,184 KB
testcase_52 AC 266 ms
11,884 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

from collections import deque

INF = 1 << 60

N, M = map(int, input().split())

graph = [[] for _ in range(N)]

for _ in range(M):
    u, v = map(int, input().split())
    u -= 1
    v -= 1
    graph[u].append(v)

def bfs(start, goal):
    visited = [False] * N
    que = deque([(start, 0)])
    
    while que:
        now, d = que.popleft()
        
        for next in graph[now]:
            if visited[next] == True:
                continue
            if next == goal:
                return d + 1
            visited[next] = True
            que.append((next, d + 1))
        
    return INF

# 町1 -> 町N-1 -> 町N -> 町1 の最短経路の長さ
ans_1 = bfs(0, N-2) + bfs(N-2, N-1) + bfs(N-1, 0)

# 町1 -> 町N -> 町N-1 -> 町1 の最短経路の長さ
ans_2 = bfs(0, N-1) + bfs(N-1, N-2) + bfs(N-2, 0)

ans = min(ans_1, ans_2)

if ans < INF:
	print(ans)
else:
	print(-1)
0