Skip to content

Instantly share code, notes, and snippets.

@siavashk
Created March 11, 2025 05:08
Show Gist options
  • Save siavashk/9987296c51e7589be3d08066483a86b9 to your computer and use it in GitHub Desktop.
Save siavashk/9987296c51e7589be3d08066483a86b9 to your computer and use it in GitHub Desktop.
def bellman_ford(n, edges, src):
dist = [float("inf")] * n
dist[src] = 0
for _ in range(n - 1):
for u, v, weight in edges:
if dist[u] != float("inf") and dist[u] + weight < dist[v]:
dist[v] = dist[u] + weight
for u, v, weight in edges:
if dist[u] != float("inf") and dist[u] + weight < dist[v]:
raise RuntimeError("Graph contains a negative weight cycle!")
return dist
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment