Search⌘ K
AI Features

Challenge: All-Pairs Shortest Paths

Explore how to implement the all-pairs shortest paths algorithm in C++. Learn to detect negative cycles using Bellman-Ford and to apply Johnson’s method with Dijkstra’s algorithm to compute shortest paths efficiently. This lesson guides you through coding and analyzing the algorithm's complexity.

Let's practice what we've 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 C++ 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
...