Skip to content

Instantly share code, notes, and snippets.

@TheAlchemistKE
Created October 22, 2023 11:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TheAlchemistKE/620454423f8518ecb307bf6c9091af3c to your computer and use it in GitHub Desktop.
Save TheAlchemistKE/620454423f8518ecb307bf6c9091af3c to your computer and use it in GitHub Desktop.
def bellman_ford(graph, source):
# Initialize distances and predecessors
distances = {vertex: float('infinity') for vertex in graph}
predecessors = {vertex: None for vertex in graph}
distances[source] = 0
# Relax edges repeatedly
for _ in range(len(graph) - 1):
for vertex in graph:
for neighbor in graph[vertex]:
if distances[vertex] + graph[vertex][neighbor] < distances[neighbor]:
distances[neighbor] = distances[vertex] + graph[vertex][neighbor]
predecessors[neighbor] = vertex
# Check for negative-weight cycles
for vertex in graph:
for neighbor in graph[vertex]:
if distances[vertex] + graph[vertex][neighbor] < distances[neighbor]:
raise Exception("Negative-weight cycle detected")
return distances, predecessors
# Test data
graph = {
'A': {'B': -1, 'C': 4},
'B': {'C': 3, 'D': 2, 'E': 2},
'C': {},
'D': {'B': 1, 'C': 5},
'E': {'D': -3}
}
source = 'A'
# Run the algorithm
distances, predecessors = bellman_ford(graph, source)
# Expected output
print("Distances:", distances)
print("Predecessors:", predecessors)
# Result:
# Distances: {'A': 0, 'B': -1, 'C': 2, 'D': -2, 'E': 1}
# Predecessors: {'A': None, 'B': 'A', 'C': 'B', 'D': 'E', 'E': 'B'}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment