Return to the current

Johnson's Algorithm - Example

Johnson's algorithm is an algorithm for finding the shortest path between every vertex in a graph, including those with negative weights.

ENFR日本語

Prerequisites

To understand the workings of Johnson’s algorithm, it’s necessary to be familiar with two other shortest path algorithms:

  1. Dijkstra’s Algorithm - Example
  2. Bellman-Ford Algorithm - Example

Idea of the Algorithm

  1. Adding a Vertex: We add a vertex ww to the graph GG along with V|V| edges connecting ww to each vertex of GG.
  2. We use Bellman-Ford’s algorithm from ww towards all other vertices of GG. d(s)d(s) gives us the distance between ww and ss. If Bellman-Ford detects a negative cycle, the algorithm stops.
  3. Removal of Vertex ww: This vertex is no longer useful. Remove this vertex and all the edges added in step 1.
  4. Re-weighting the Edges of the Graph: For each edge (u,v)(u,v) in the graph, do: p((u,v)):=p((u,v))+d(u)d(v)p((u,v)) := p((u,v)) + d(u) - d(v).
  5. Calculating the Shortest Path: For each vertex in GG, apply Dijkstra’s algorithm to determine the shortest path between all vertices.

It is important to note that the distances are not preserved. If for an edge, we had a weight of 2-2, the new weight will be 0\geq 0. However, this is not the point. Johnson’s algorithm gives us the shortest path from point AA to point BB “only”. If you need to retrieve the sum of the weights of this path, just return to the original graph and follow the path given by Johnson.

Algorithm / Solution / Complexity

This article only presents an example of the application of Johnson’s algorithm. However, you can easily find this information on the internet:

Example:

Let GG be a graph with negative weight edges.

Initial Graph

Step 1 - Adding Vertex w

Adding w

Step 2 - Shortest Paths from w to Other Vertices Using Bellman-Ford

Shortest Paths Added

In purple are the results of Bellman-Ford’s algorithm.

Steps 3 and 4 - Re-weighting the Edges

Re-weighting of Edges

Step 5 - Dijkstra’s Algorithm on All Edges

The final graph GG' is as follows:

Graph G'

Step 5 is simply an application of Dijkstra’s algorithm. An example of its use is already detailed on this site: Dijkstra’s Algorithm - Example.

To take multiple results from Dijkstra’s algorithm:

  • To go from a to d, the path to take is abcda \rightarrow b \rightarrow c \rightarrow d with a weight of -9 (not 0, the weights from GG and not GG' must be used).
  • To go from f to d, the path to take is fecdf \rightarrow e \rightarrow c \rightarrow d with a weight of -2.
  • There is no possible path from d to e.

The rest is left as an exercise for the reader.