Guest User
Using app without sign in

Practice book
Graph Theory Through Problems300 Exercises with Hints, Worked Algorithms and Complete Solutions
By Mohammed Islam Hadjoudj
Learn graph theory by solving problems: 300 exercises, from routine checks to challenging proofs, each with a complete solution.
Also by the authorGraph Algorithms for Coding Interviews100 solved interview problems with visual explanations and Python solutions.View on AmazonSelect an algorithm and generate steps to begin visualization
All-pairs shortest paths with negative edges
All-pairs shortest paths with negative edges: Bellman-Ford potentials, reweighting, then Dijkstra from every vertex
Select an algorithm and generate steps to begin visualization
Johnson's algorithm computes the shortest path between every pair of vertices in a weighted directed graph, even when some edges have negative weights, as long as there is no negative cycle. Donald B. Johnson published it in 1977. It combines Bellman-Ford and Dijkstra, and on sparse graphs it is much faster than running Floyd-Warshall.
The algorithm adds a new vertex q with a 0-weight edge to every vertex and runs Bellman-Ford from q. The distance h(v) from q becomes the potential of v, and Bellman-Ford also reports a negative cycle if one exists. Every edge is then reweighted to w'(u, v) = w(u, v) + h(u) - h(v), which is never negative, and every path between two vertices changes by the same amount, so shortest paths stay shortest. Finally Dijkstra runs from every vertex on the new weights, and each result is converted back with d'(v) - h(u) + h(v). The total cost is O(VE log V) with a binary heap.
Johnson's algorithm answers all-pairs distance queries on large sparse networks such as road maps, routing tables and dependency graphs, where V³ time would be too slow. Negative weights appear in arbitrage and cost-reduction models, and reweighting by potentials is the same idea used in min-cost flow algorithms. In courses it is the classic example of making Dijkstra work on graphs with negative edges.
Read the full article: Shortest Path Algorithms Explained
Read the full article: Dijkstra vs Bellman-Ford vs Floyd-Warshall
Related algorithms: Floyd-Warshall Algorithm, Bellman-Ford Algorithm, Dijkstra's Algorithm, A* Search Algorithm