learngraphtheory.org

Guest User

Using app without sign in

Cover of the book Graph Theory Through Problems

Practice book

Graph Theory Through Problems

300 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.

Available inKindlePaperback

13 chapters

Also by the authorGraph Algorithms for Coding Interviews100 solved interview problems with visual explanations and Python solutions.View on Amazon
Algorithm Selection

Select an algorithm and generate steps to begin visualization

Johnson's Algorithm Calculator

All-pairs shortest paths with negative edges

All-pairs shortest paths with negative edges: Bellman-Ford potentials, reweighting, then Dijkstra from every vertex

Time: O(VE log V)
Space: O(V²)
Use Case: All-pairs distances on sparse graphs with negative weights
Showing the example graph for this algorithm.
Algorithm Execution

Select an algorithm and generate steps to begin visualization

About Johnson's Algorithm

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.

How it works

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.

Applications

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.

Related algorithms: Floyd-Warshall Algorithm, Bellman-Ford Algorithm, Dijkstra's Algorithm, A* Search Algorithm

Interactive Controls

Zoom Controls

46%
Nodes: 5
Edges: 9