Skip to contentKEEP THE CRAFTTHE SANCTUARY

Relax Signed Edges with Bellman-Ford

Find cheapest paths when weights can be negative by relaxing every edge in rounds, and detect a reachable negative cycle.

The problem

Implement bellman_ford_distances(node_count, edges, source). The nodes are labeled 0 to node_count - 1, and each edge [u, v, weight] goes one way, from u to v. Weights may be negative. Return a list whose entry i is the cost of the cheapest path from source to node i, or -1 if node i cannot be reached. If the source can reach a negative cycle (a loop whose weights add up to less than 0), costs could drop forever, so return [] instead; a negative cycle the source cannot reach does not matter. For example, with edges [[0, 1, 4], [0, 2, 5], [1, 2, -3], [2, 3, 2]] and source 0 the answer is [0, 4, 1, 3].

Starter code

def bellman_ford_distances(node_count, edges, source):
    pass

Public examples

  1. node_count = 4, edges = [[0, 1, 4], [0, 2, 5], [1, 2, -3], [2, 3, 2]], source = 0gives[0, 4, 1, 3]
  2. node_count = 3, edges = [[0, 1, 1], [1, 2, -2], [2, 1, -2]], source = 0gives[]

Solving it in the practice book needs an active paid plan.

Open it in the practice book
One thought at a time.