벨만-포드 알고리즘은 그래프에서 한 정점으로부터 다른 모든 정점까지의 최단 경로를 찾는 알고리즘이다. 다익스트라 알고리즘과 달리 음수 가중치를 가진 간선이 있는 경우에도 사용할 수 있다.
벨만-포드 알고리즘은 다음과 같은 단계로 동작합니다:
def bellman_ford(graph, start, V):
# 거리 초기화
distance = [float('inf')] * V
distance[start] = 0
# V-1번 반복
for _ in range(V-1):
for u, v, w in graph:
if distance[u] != float('inf') and distance[u] + w < distance[v]:
distance[v] = distance[u] + w
# 음수 사이클 검사
for u, v, w in graph:
if distance[u] != float('inf') and distance[u] + w < distance[v]:
return None # 음수 사이클 존재
return distance