Replies: 1 comment 1 reply
-
def bellman_ford(edges, n_vertex, start):
"""
edges[n] -> (orig, dest, weight): n번째 간선. orig에서 dest로 거리는 weight
n_vertex: 정점의 수
start: 시작 정점 번호 x
distance_table[n] -> x: 시작점부터 정점 n까지의 최단 거리 x
parent_table[n] -> x: 시작점부터 정점 n까지의 최단 경로 중, 정점n 오기 직전에 지난 정점 번호 x
"""
distance_table = [float("inf")] * n_vertex
parent_table = [None] * n_vertex
distance_table[start] = 0
# 모든 간선에 대해서 업데이트
def iter():
for orig, dest, weight in edges:
old_path_distance = distance_table[dest]
new_path_distance = distance_table[orig] + weight
if old_path_distance > new_path_distance:
distance_table[dest] = new_path_distance
parent_table[dest] = orig
# iter()을 정점의 수만큼 반복
for _ in range(n_vertex):
iter()
# 음의 싸이클에 포함된 정점들을 탐지
for orig, dest, weight in edges:
old_path_distance = distance_table[dest]
new_path_distance = distance_table[orig] + weight
if old_path_distance > new_path_distance:
distance_table[dest] = float("-inf")
parent_table[dest] = None
print(distance_table)
print(parent_table) 주어진 예시에서 |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
(1) 입력:
예시 :
5 8
0 1 -1
0 2 4
1 2 3
1 3 2
1 4 2
3 2 5
3 1 1
4 3 -3
0
(2) 출력: 시작 노드에서 각 노드로의 최단 거리를 출력한다.
예시 :
Shortest distances from source(0):
0 0 2 -1 -3
Shortest paths:
0 to 0: 0
0 to 1: 0 -> 1
0 to 2: 0 -> 1 -> 2
0 to 3: 0 -> 1 -> 3
0 to 4: 0 -> 1 -> 3 -> 4
(3) if name = “main”:에서 테스트을 수행한다.
Beta Was this translation helpful? Give feedback.
All reactions