Solution: All-Pairs Shortest Paths
Explore the implementation of Johnson’s algorithm for solving all-pairs shortest paths in a weighted graph. Understand how to detect negative cycles with Bellman-Ford, reweight edges, and run Dijkstra’s algorithm efficiently in Java. Gain practical skills by analyzing and coding this solution to enhance your algorithmic problem-solving.
We'll cover the following...
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 , if one exists, instead of only reporting whether or not contains a negative cycle. Analyze the provided algorithm and then provide its Java 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
- Let be the input graph, with vertices and edges .
- Add a new vertex to and add zero-weight edges from to all vertices in .
- Run the Bellman-Ford algorithm with as the source vertex to compute a new set of edge weights that satisfy the following property: for any edge