Search⌘ K

Solution: All-Pairs Shortest Paths

Explore the implementation of Johnson's algorithm for computing all-pairs shortest paths in graphs. Understand how the algorithm detects negative cycles using Bellman-Ford, adjusts edge weights, and then applies Dijkstra's algorithm for optimized shortest path calculation. This lesson equips you to analyze and code this complex algorithm in Python while grasping its time complexity and practical applications.

Let's practice what we have learned so far.

Task

The algorithms described in this chapter can also be modified to return an explicit description of some negative cycle in the input graph GG, if one exists, instead of only reporting whether or not GG contains a negative cycle. Analyze the provided algorithm and then provide its Python implementation in the coding workspace provided below.

Logic building

Here’s an algorithm for the modified version of Johnson’s algorithm that returns either the array of all shortest path distances or a negative cycle.

Algorithm


  1. Let G=(V,E)G = (V, E) be the input graph, with vertices VV and edges EE.

  2. Add a new vertex ss to GG and add zero-weight edges from ss to all vertices in VV.

  3. Run the Bellman-Ford algorithm with ss as the source vertex to compute a new set of edge weights h:E>Rh: E -> R that satisfy the following property: for any edge (u,v)(u, v) ...