forked from ndb796/python-for-coding-test
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path4.py
More file actions
38 lines (31 loc) ยท 1.23 KB
/
4.py
File metadata and controls
38 lines (31 loc) ยท 1.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
INF = int(1e9) # ๋ฌดํ์ ์๋ฏธํ๋ ๊ฐ์ผ๋ก 10์ต์ ์ค์
# ๋
ธ๋์ ๊ฐ์ ๋ฐ ๊ฐ์ ์ ๊ฐ์๋ฅผ ์
๋ ฅ๋ฐ๊ธฐ
n, m = map(int, input().split())
# 2์ฐจ์ ๋ฆฌ์คํธ(๊ทธ๋ํ ํํ)๋ฅผ ๋ง๋ค๊ณ , ๋ชจ๋ ๊ฐ์ ๋ฌดํ์ผ๋ก ์ด๊ธฐํ
graph = [[INF] * (n + 1) for _ in range(n + 1)]
# ์๊ธฐ ์์ ์์ ์๊ธฐ ์์ ์ผ๋ก ๊ฐ๋ ๋น์ฉ์ 0์ผ๋ก ์ด๊ธฐํ
for a in range(1, n + 1):
for b in range(1, n + 1):
if a == b:
graph[a][b] = 0
# ๊ฐ ๊ฐ์ ์ ๋ํ ์ ๋ณด๋ฅผ ์
๋ ฅ ๋ฐ์, ๊ทธ ๊ฐ์ผ๋ก ์ด๊ธฐํ
for _ in range(m):
# A์ B๊ฐ ์๋ก์๊ฒ ๊ฐ๋ ๋น์ฉ์ 1์ด๋ผ๊ณ ์ค์
a, b = map(int, input().split())
graph[a][b] = 1
graph[b][a] = 1
# ๊ฑฐ์ณ ๊ฐ ๋
ธ๋ X์ ์ต์ข
๋ชฉ์ ์ง ๋
ธ๋ K๋ฅผ ์
๋ ฅ๋ฐ๊ธฐ
x, k = map(int, input().split())
# ์ ํ์์ ๋ฐ๋ผ ํ๋ก์ด๋ ์์
์๊ณ ๋ฆฌ์ฆ์ ์ํ
for k in range(1, n + 1):
for a in range(1, n + 1):
for b in range(1, n + 1):
graph[a][b] = min(graph[a][b], graph[a][k] + graph[k][b])
# ์ํ๋ ๊ฒฐ๊ณผ๋ฅผ ์ถ๋ ฅ
distance = graph[1][k] + graph[k][x]
# ๋๋ฌํ ์ ์๋ ๊ฒฝ์ฐ, -1์ ์ถ๋ ฅ
if distance >= 1e9:
print("-1")
# ๋๋ฌํ ์ ์๋ค๋ฉด, ์ต๋จ ๊ฑฐ๋ฆฌ๋ฅผ ์ถ๋ ฅ
else:
print(distance)