Created
March 11, 2025 05:08
-
-
Save siavashk/9987296c51e7589be3d08066483a86b9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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