We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Bellman-Ford Code

Now let's put the whole algorithm together.

We recently updated the Mappy app to allow food delivery drivers to use it more effectively. Instead of the "cost" of a given route being measured only by driving time, we're also applying a "negative cost" to routes that allow the driver to fuel up. This means Dijkstra's algorithm won't work anymore for finding the shortest path, because some routes will actually have negative values.

Assignment

Complete the bellman_ford function. Its job is to return the shortest distance between two nodes in a graph. The graph will be weighted and directed. If a negative cycle exists in the graph, the function should raise the exception negative cycle detected!.

Inputs

  • graph: an adjacency list of the nodes in the directed graph (graph[node1][node2] = weight_of_edge)
  • src: the label of the source node
  • dest: the label of the destination node

Outputs

  • distance: an integer representing the length of the shortest route

Algorithm

      • negative cycle detected!