PythiloLesson 26 of 32 · progress kept in this browser

Practice in Lab: Bellman–Ford →

Handle negative costs with Bellman-Ford

Dijkstra's algorithm breaks when an edge can lower a cost after a node is settled. Bellman-Ford instead relaxes every edge again and again. A shortest path uses at most n - 1 edges, so n - 1 rounds are enough.

edges = [("a", "b", 4), ("a", "c", 2),
         ("c", "b", -3)]
# a -> c -> b costs -1, cheaper than a -> b
Your task

Write bellman_ford(nodes, edges, start) with edges as (u, v, cost). Return a dict of cheapest costs to reachable nodes, or None when a negative cycle is reachable from start.