- Notifications
You must be signed in to change notification settings - Fork 846
/
Copy path4.py
38 lines (31 loc) · 1.23 KB
/
4.py
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_inrange(n+1)]
# 자기 자신에서 자기 자신으로 가는 비용은 0으로 초기화
forainrange(1, n+1):
forbinrange(1, n+1):
ifa==b:
graph[a][b] =0
# 각 간선에 대한 정보를 입력 받아, 그 값으로 초기화
for_inrange(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())
# 점화식에 따라 플로이드 워셜 알고리즘을 수행
forkinrange(1, n+1):
forainrange(1, n+1):
forbinrange(1, n+1):
graph[a][b] =min(graph[a][b], graph[a][k] +graph[k][b])
# 수행된 결과를 출력
distance=graph[1][k] +graph[k][x]
# 도달할 수 없는 경우, -1을 출력
ifdistance>=1e9:
print("-1")
# 도달할 수 있다면, 최단 거리를 출력
else:
print(distance)