Johnson's Algorithm in C++ — All-Pairs Shortest Paths for Sparse Graphs (with Negatives)

Explore this blog post in detail

Blog Images

3 images
Blog Images - Image 1
Swipe
1 / 3

Johnson's Algorithm in C++ — All-Pairs Shortest Paths for Sparse Graphs (with Negatives)

Mashrur Rahman
8/12/2025
Graph Algorithms
Published
# Johnson's Algorithm — All-Pairs Shortest Paths (C++) ## Overview Johnson's algorithm computes all-pairs shortest paths for sparse graphs that may contain negative edges (but not negative cycles). It uses Bellman–Ford once to reweight edges, then runs Dijkstra from each vertex. ## Steps 1. Add a new node connected to every vertex with edge weight 0. 2. Run Bellman–Ford from the new node to compute vertex potentials `h[v]`. 3. Reweight original edges: `w'(u,v) = w(u,v) + h[u] - h[v]` (non-negative). 4. Run Dijkstra from each vertex on reweighted graph, then convert distances back: `dist(u,v) = dist'(u,v) - h[u] + h[v]`. ## Complexity - Bellman–Ford: **O(V·E)** - Dijkstra per vertex: `V * O(E log V)` (with heap) - Good for **sparse** graphs vs Floyd–Warshall on dense graphs. ## Repo `https://github.com/mashrur-rahman-fahim/algorithm/blob/main/johnson.cpp` implements this flow and reweights edges in-place. ## Practical tips - Must check for negative cycles with Bellman–Ford. - Use an efficient priority queue for Dijkstra. ## Source `https://github.com/mashrur-rahman-fahim/algorithm/blob/main/johnson.cpp`.

Technologies & Tools

C++Graph AlgorithmsJohnsonBellman–FordDijkstraVS CodeG++ CompilerGitGitHub

About the Author

External Links

Blog Info

Status:Published
Type:Algorithm Analysis
Category:Graph Algorithms
Author:Mashrur Rahman
Created:8/12/2025

About the Author

M

Mashrur Rahman

Blog Author

Comments (0)

No comments yet. Be the first to comment!

Mashrur Rahman

A passionate full-stack developer dedicated to creating innovative digital solutions that make a difference. Let's build something amazing together.

Get In Touch

Email

mashrur9550@gmail.com

Location

Dhaka, Bangladesh

© 2026 Mashrur Rahman. All rights reserved.