Shortest Path Problem
Find the shortest path from
Theory
Iteratively try to relax each edge, using it if it creates a better shortest path.
Since a path can use at most
Implementation
def bellman_ford(s, adj):
dist = [float('inf') for _ in range(len(adj)]
dist[s] = 0
for _ in range(len(adj)-1):
for u in adj:
for v, w in adj[u]:
if dist[u] + w < dist[v]:
dist[v] = dist[u] + w
for u in adj:
for v, w in adj[u]:
if dist[u] + w < dist[v]:
return None, True
return dist, False
Runtime
We loop over all edges