

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Still calibrating
click for more info
Not enough gems
Cost: 6 gems
1: Directed and Undirected Graphs
incomplete
2: Cycles in Graphs
incomplete
3: Bellman-Ford Algorithm
incomplete
4: Edge Relaxation
incomplete
5: Bellman-Ford Code
incomplete
6: Bellman-Ford Review
incomplete
This lesson's interactive features are locked, please to keep using them
"Relaxing" an edge means checking if the currently known shortest distance to a node can be improved by following a different edge. If it can, we update its shortest known distance.
Take a look at this graph:
Imagine that we've already found the path from A to C through B, with a total cost of 9. We would have a distances dictionary like this:
distances = {"A": 0, "B": 5, "C": 9}
Then we check the path directly from A to C, which has a cost of 7. Since this is lower than the current known cost of 9, we "relax" the edge and update distances accordingly.
Trouble is, if a graph has a negative cycle, we could keep relaxing its edges forever, with the "shortest distance" decreasing every time.
Part of the genius of the Bellman-Ford algorithm is recognizing that the maximum number of edges in any shortest path is n-1, where n is the number of nodes. So if we perform n-1 iterations of edge relaxation, we will definitely have found the shortest paths to all nodes – unless there's a negative cycle.
In Bellman-Ford, we try an nth iteration of edge relaxation, and if any paths continue to shorten, we know a negative cycle exists. We can then raise an exception or return an error value, since the graph is ill-formed.
Complete the relax_edge function. This is a key part of the Bellman-Ford algorithm.
total_distances: a dictionary mapping nodes to their current shortest distance from the source nodenode_a: the label of the starting node of the edge in questionnode_b: the label of the ending node of the edge in questiondist_a_b: the weight of the edge from node_a to node_bTrue or False, based on whether the edge was relaxed, i.e., whether a new shortest distance to node_b was found. (If so, you'll also update total_distances[node_b]; but only the boolean is returned.)