Finding shortest paths between every pair of vertices is harder when a sparse directed graph contains negative edges. Repeating Bellman–Ford from every source is expensive, while Dijkstra’s algorithm requires nonnegative weights. Johnson’s algorithm computes one potential h(v) for each vertex using Bellman–Ford, reweights every edge so it becomes nonnegative, runs Dijkstra from every source, then converts distances back. Mathematics matters because the transformation preserves the order and weight differences of complete paths through telescoping endpoint terms. It changes the arithmetic landscape without changing which routes are shortest.
The practical search question is not simply “what is this named method?” but “which mathematical structure makes the method work, what does it guarantee, and what evidence would show that it is a poor choice?” This article keeps those questions together so students can connect mathematics education with computing, engineering, data reasoning and careful everyday decisions without turning one technique into a career promise.
Quick navigation: Why it matters · Mechanism · Worked example · Deeper ideas · Investigations · Limits · Learning route · Parent guidance · FAQs · Sources
Why this mathematics matters
Mathematics is important here because it turns an apparently visual or computational trick into a chain of reasons. The representation tells us what information is kept. The equation or invariant explains each legal step. The complexity analysis describes the work. The boundary conditions say when a conclusion should not be trusted. That combination is a practical form of problem-solving literacy.
A strong learner should be able to move in both directions: from a real task to a mathematical model, and from a formal guarantee back to its real meaning. Naming an algorithm is not enough. The useful achievement is to explain why the next operation is valid, check a small instance independently, and notice which assumptions the implementation has added.
Source: Donald B. Johnson’s 1977 Journal of the ACM paper on sparse-network shortest paths.
Primary or implementation reference: NIST Dictionary of Algorithms and Data Structures entry for Johnson’s algorithm.
How the mechanism works
Add a new vertex q with a zero-weight edge to every original vertex. Run Bellman–Ford from q. If it finds a negative cycle, stop because finite all-pairs shortest paths are not defined for affected pairs. Otherwise set h(v)=distance(q,v). Reweight each original edge u→v of weight w to w′=w+h(u)−h(v). The Bellman–Ford inequalities guarantee w′≥0. Run Dijkstra from each original source using w′. Convert each finite result back with d(u,v)=d′(u,v)−h(u)+h(v). Preserve infinity for unreachable pairs and use wide arithmetic.
For any path P from s to t, summing reweighted edges cancels the intermediate potentials: w′(P)=w(P)+h(s)−h(t). Every s-to-t path receives the same endpoint offset, so a path minimises original weight exactly when it minimises reweighted weight. Bellman–Ford gives h(v)≤h(u)+w(u,v), rearranging to w+h(u)−h(v)≥0. With a binary heap, the full method is commonly bounded by O(VE+V(E+V)log V), attractive for sparse graphs compared with cubic all-pairs methods. The transformation preserves shortest paths, not individual edge magnitudes.
Keep a four-column notebook labelled object, rule, guarantee and caveat. In the first column name the inputs and stored state. In the second write one update precisely. In the third state what remains true after the update. In the fourth record a tie, approximation, domain restriction or hardware assumption. This routine prevents symbols from drifting away from their meaning.
Worked example and core calculations
Use A→B=1, B→C=−2, A→C=4, C→D=2 and B→D=5. Adding q with zero edges gives potentials h(A)=0, h(B)=0, h(C)=−2 and h(D)=0. Reweighted edges become A→B=1, B→C=0, A→C=6, C→D=0 and B→D=5, all nonnegative. Dijkstra from A finds reweighted distances B=1, C=1 and D=1. Convert back: d(A,B)=1, d(A,C)=1−0+(−2)=−1, and d(A,D)=1. Directly, A→B→C has 1−2=−1 and A→B→C→D has 1−2+2=1, confirming the transformation.
How to audit the calculation
- Recompute every intermediate value directly from the definition.
- Keep labels, indices, signs, units and normalisation visible.
- Test a case with a known exact answer.
- State tie rules, random seeds, tolerances and boundary conventions.
- Compare with a slower transparent baseline or trusted implementation.
- Separate agreement of numbers from suitability of the real-world model.
Small examples are not childish; they are diagnostic instruments. A five-line trace can reveal a reversed inequality, a missing scale factor or an inconsistent label convention before a large dataset hides the same error behind plausible output.
Four deeper ideas
Potentials behave like a change of reference level
They redistribute cost among edges while every complete path keeps only an endpoint-dependent offset.
To transfer this idea, ask what would remain true if labels, scale or input order changed. Then identify the step whose justification would fail if the stated assumption were removed. This turns the paragraph into a reusable reasoning pattern rather than a fact to memorise.
Did you know? Zero edges make every vertex reachable for preprocessing
The artificial source lets one Bellman–Ford run generate valid potentials across disconnected components.
To transfer this idea, ask what would remain true if labels, scale or input order changed. Then identify the step whose justification would fail if the stated assumption were removed. This turns the paragraph into a reusable reasoning pattern rather than a fact to memorise.
Nonnegative reweighting unlocks a faster subroutine
The point is not aesthetic positivity; it makes repeated Dijkstra runs legally available.
To transfer this idea, ask what would remain true if labels, scale or input order changed. Then identify the step whose justification would fail if the stated assumption were removed. This turns the paragraph into a reusable reasoning pattern rather than a fact to memorise.
Telescoping is the preservation proof
Intermediate +h(v) and −h(v) terms cancel, so relative path ordering between fixed endpoints survives.
To transfer this idea, ask what would remain true if labels, scale or input order changed. Then identify the step whose justification would fail if the stated assumption were removed. This turns the paragraph into a reusable reasoning pattern rather than a fact to memorise.
Twelve practical investigations
1. Four-vertex graph
Use the worked edges. Compute every potential and new weight.
What the mathematics reveals: Telescoping preserves distances. Evidence to collect: write the input, predict the next state, carry out the calculation, and compare the result with an independently produced reference. Explain the exact invariant, equation, inequality or counting rule that supports the conclusion. Then vary one assumption and record whether the result changes smoothly, discontinuously or not at all.
Limit to keep visible: Check all new weights. A useful report places this boundary beside the result rather than hiding it in a final disclaimer.
2. Disconnected graph
Use two components. Connect q to every vertex.
What the mathematics reveals: One preprocessing run covers both components. Evidence to collect: write the input, predict the next state, carry out the calculation, and compare the result with an independently produced reference. Explain the exact invariant, equation, inequality or counting rule that supports the conclusion. Then vary one assumption and record whether the result changes smoothly, discontinuously or not at all.
Limit to keep visible: Keep unreachable pairs infinite. A useful report places this boundary beside the result rather than hiding it in a final disclaimer.
3. Negative cycle
Add D→B with sufficiently negative weight. Run Bellman–Ford.
What the mathematics reveals: Potentials cannot legalise unbounded routes. Evidence to collect: write the input, predict the next state, carry out the calculation, and compare the result with an independently produced reference. Explain the exact invariant, equation, inequality or counting rule that supports the conclusion. Then vary one assumption and record whether the result changes smoothly, discontinuously or not at all.
Limit to keep visible: Stop before Dijkstra. A useful report places this boundary beside the result rather than hiding it in a final disclaimer.
4. No negative edges
Use ordinary road weights. Compare with repeated Dijkstra.
What the mathematics reveals: Johnson remains valid with extra preprocessing. Evidence to collect: write the input, predict the next state, carry out the calculation, and compare the result with an independently produced reference. Explain the exact invariant, equation, inequality or counting rule that supports the conclusion. Then vary one assumption and record whether the result changes smoothly, discontinuously or not at all.
Limit to keep visible: Choose simpler methods when suitable. A useful report places this boundary beside the result rather than hiding it in a final disclaimer.
5. Dense graph
Add most possible edges. Compare with Floyd–Warshall.
What the mathematics reveals: Sparsity controls the advantage. Evidence to collect: write the input, predict the next state, carry out the calculation, and compare the result with an independently produced reference. Explain the exact invariant, equation, inequality or counting rule that supports the conclusion. Then vary one assumption and record whether the result changes smoothly, discontinuously or not at all.
Limit to keep visible: Benchmark real sizes. A useful report places this boundary beside the result rather than hiding it in a final disclaimer.
6. Parallel edges
Store two u→v costs. Reweight both.
What the mathematics reveals: Endpoint offsets are identical. Evidence to collect: write the input, predict the next state, carry out the calculation, and compare the result with an independently produced reference. Explain the exact invariant, equation, inequality or counting rule that supports the conclusion. Then vary one assumption and record whether the result changes smoothly, discontinuously or not at all.
Limit to keep visible: Do not overwrite edges. A useful report places this boundary beside the result rather than hiding it in a final disclaimer.
7. Potential shift
Add a constant to all h values. Recompute weights.
What the mathematics reveals: Only potential differences matter. Evidence to collect: write the input, predict the next state, carry out the calculation, and compare the result with an independently produced reference. Explain the exact invariant, equation, inequality or counting rule that supports the conclusion. Then vary one assumption and record whether the result changes smoothly, discontinuously or not at all.
Limit to keep visible: Distances convert consistently. A useful report places this boundary beside the result rather than hiding it in a final disclaimer.
8. Overflow
Use large positive and negative weights. Bound h and transformed sums.
What the mathematics reveals: Algebraic validity does not prevent machine overflow. Evidence to collect: write the input, predict the next state, carry out the calculation, and compare the result with an independently produced reference. Explain the exact invariant, equation, inequality or counting rule that supports the conclusion. Then vary one assumption and record whether the result changes smoothly, discontinuously or not at all.
Limit to keep visible: Use safe types. A useful report places this boundary beside the result rather than hiding it in a final disclaimer.
9. Path reconstruction
Keep Dijkstra predecessors. Map route vertices back directly.
What the mathematics reveals: Reweighting changes costs, not path identities. Evidence to collect: write the input, predict the next state, carry out the calculation, and compare the result with an independently produced reference. Explain the exact invariant, equation, inequality or counting rule that supports the conclusion. Then vary one assumption and record whether the result changes smoothly, discontinuously or not at all.
Limit to keep visible: Convert only distances. A useful report places this boundary beside the result rather than hiding it in a final disclaimer.
10. Matrix output
Materialise all d(u,v). Count memory.
What the mathematics reveals: Output itself can dominate space. Evidence to collect: write the input, predict the next state, carry out the calculation, and compare the result with an independently produced reference. Explain the exact invariant, equation, inequality or counting rule that supports the conclusion. Then vary one assumption and record whether the result changes smoothly, discontinuously or not at all.
Limit to keep visible: Stream rows if appropriate. A useful report places this boundary beside the result rather than hiding it in a final disclaimer.
11. Bellman–Ford oracle
Run it from every source on a tiny graph. Compare distances.
What the mathematics reveals: A slower independent method validates the pipeline. Evidence to collect: write the input, predict the next state, carry out the calculation, and compare the result with an independently produced reference. Explain the exact invariant, equation, inequality or counting rule that supports the conclusion. Then vary one assumption and record whether the result changes smoothly, discontinuously or not at all.
Limit to keep visible: Match cycle semantics. A useful report places this boundary beside the result rather than hiding it in a final disclaimer.
12. Property test
Generate graphs from safe potentials. Compare original and reweighted path orders.
What the mathematics reveals: Telescoping is testable. Evidence to collect: write the input, predict the next state, carry out the calculation, and compare the result with an independently produced reference. Explain the exact invariant, equation, inequality or counting rule that supports the conclusion. Then vary one assumption and record whether the result changes smoothly, discontinuously or not at all.
Limit to keep visible: Retain seeds. A useful report places this boundary beside the result rather than hiding it in a final disclaimer.
Limits and misconceptions
Johnson’s algorithm rejects graphs with negative cycles because shortest distances can be unbounded below for relevant pairs. It may be slower than Floyd–Warshall on dense graphs or small matrices. A correct Dijkstra implementation and priority queue still matter. Reweighting can enlarge numeric ranges, so overflow checks are essential. Infinity must not participate in arithmetic. The graph can be directed, and parallel edges need correct storage. All-pairs distance tables require O(V²) output space if fully materialised. A shortest numeric route does not model capacity, risk, reliability, policy or multiple objectives unless those are responsibly encoded.
Five misconceptions to challenge
- Reweighting changes the chosen shortest path: Every fixed-endpoint path receives the same offset.
- All original edges must be nonnegative: Bellman–Ford potentials can transform negative edges when no negative cycle exists.
- The new vertex remains in the final graph: It is only a preprocessing device.
- One Dijkstra run gives all pairs: Dijkstra runs once from each original source.
- A negative cycle can be ignored after reweighting: It prevents valid potentials and finite shortest-path guarantees.
Another broad misconception is that advanced mathematics automatically creates intelligence, admission, income or employment. It does not. Deliberate study can strengthen modelling, abstraction, calculation and explanation, while real pathways also depend on interests, communication, domain knowledge, opportunities and circumstances outside one topic.
A learning route for students
Move from a visible trace to a symbolic rule, then to code and critique. For every step below, prepare three pieces of evidence: a correct hand example, a boundary or failure case, and a short explanation using the relevant invariant. Do not advance merely because software returned a number.
Step 1: Define all-pairs shortest paths
Begin with the smallest non-trivial instance that lets you define all-pairs shortest paths. Predict the result before calculating. Write each state change clearly enough that another student can reproduce it. Compare with a trusted implementation only after the hand trace is complete.
Next, change one feature—size, ordering, sign, tolerance, labelling or data distribution—and explain which part of the reasoning changes. Finish by teaching the step without code and by naming one input for which the method is unhelpful. This predict–calculate–vary–explain cycle is a strong test of transferable understanding.
Step 2: Run bellman–ford preprocessing
Begin with the smallest non-trivial instance that lets you run Bellman–Ford preprocessing. Predict the result before calculating. Write each state change clearly enough that another student can reproduce it. Compare with a trusted implementation only after the hand trace is complete.
Next, change one feature—size, ordering, sign, tolerance, labelling or data distribution—and explain which part of the reasoning changes. Finish by teaching the step without code and by naming one input for which the method is unhelpful. This predict–calculate–vary–explain cycle is a strong test of transferable understanding.
Step 3: Compute vertex potentials
Begin with the smallest non-trivial instance that lets you compute vertex potentials. Predict the result before calculating. Write each state change clearly enough that another student can reproduce it. Compare with a trusted implementation only after the hand trace is complete.
Next, change one feature—size, ordering, sign, tolerance, labelling or data distribution—and explain which part of the reasoning changes. Finish by teaching the step without code and by naming one input for which the method is unhelpful. This predict–calculate–vary–explain cycle is a strong test of transferable understanding.
Step 4: Reweight an edge
Begin with the smallest non-trivial instance that lets you reweight an edge. Predict the result before calculating. Write each state change clearly enough that another student can reproduce it. Compare with a trusted implementation only after the hand trace is complete.
Next, change one feature—size, ordering, sign, tolerance, labelling or data distribution—and explain which part of the reasoning changes. Finish by teaching the step without code and by naming one input for which the method is unhelpful. This predict–calculate–vary–explain cycle is a strong test of transferable understanding.
Step 5: Prove nonnegative transformed weights
Begin with the smallest non-trivial instance that lets you prove nonnegative transformed weights. Predict the result before calculating. Write each state change clearly enough that another student can reproduce it. Compare with a trusted implementation only after the hand trace is complete.
Next, change one feature—size, ordering, sign, tolerance, labelling or data distribution—and explain which part of the reasoning changes. Finish by teaching the step without code and by naming one input for which the method is unhelpful. This predict–calculate–vary–explain cycle is a strong test of transferable understanding.
Step 6: Use telescoping sums
Begin with the smallest non-trivial instance that lets you use telescoping sums. Predict the result before calculating. Write each state change clearly enough that another student can reproduce it. Compare with a trusted implementation only after the hand trace is complete.
Next, change one feature—size, ordering, sign, tolerance, labelling or data distribution—and explain which part of the reasoning changes. Finish by teaching the step without code and by naming one input for which the method is unhelpful. This predict–calculate–vary–explain cycle is a strong test of transferable understanding.
Step 7: Run repeated dijkstra
Begin with the smallest non-trivial instance that lets you run repeated Dijkstra. Predict the result before calculating. Write each state change clearly enough that another student can reproduce it. Compare with a trusted implementation only after the hand trace is complete.
Next, change one feature—size, ordering, sign, tolerance, labelling or data distribution—and explain which part of the reasoning changes. Finish by teaching the step without code and by naming one input for which the method is unhelpful. This predict–calculate–vary–explain cycle is a strong test of transferable understanding.
Step 8: Convert distances back
Begin with the smallest non-trivial instance that lets you convert distances back. Predict the result before calculating. Write each state change clearly enough that another student can reproduce it. Compare with a trusted implementation only after the hand trace is complete.
Next, change one feature—size, ordering, sign, tolerance, labelling or data distribution—and explain which part of the reasoning changes. Finish by teaching the step without code and by naming one input for which the method is unhelpful. This predict–calculate–vary–explain cycle is a strong test of transferable understanding.
Step 9: Handle infinity and overflow
Begin with the smallest non-trivial instance that lets you handle infinity and overflow. Predict the result before calculating. Write each state change clearly enough that another student can reproduce it. Compare with a trusted implementation only after the hand trace is complete.
Next, change one feature—size, ordering, sign, tolerance, labelling or data distribution—and explain which part of the reasoning changes. Finish by teaching the step without code and by naming one input for which the method is unhelpful. This predict–calculate–vary–explain cycle is a strong test of transferable understanding.
Step 10: Compare sparse and dense algorithms
Begin with the smallest non-trivial instance that lets you compare sparse and dense algorithms. Predict the result before calculating. Write each state change clearly enough that another student can reproduce it. Compare with a trusted implementation only after the hand trace is complete.
Next, change one feature—size, ordering, sign, tolerance, labelling or data distribution—and explain which part of the reasoning changes. Finish by teaching the step without code and by naming one input for which the method is unhelpful. This predict–calculate–vary–explain cycle is a strong test of transferable understanding.
A four-week practice plan
- Week 1 — vocabulary and diagrams: define each object, redraw the mechanism and reproduce the worked example.
- Week 2 — equations and manufactured tests: derive the key relation and test inputs with known answers.
- Week 3 — implementation and evidence: use a trusted library, record parameters and compare with a transparent baseline.
- Week 4 — transfer and critique: apply the method to a new context, report limits and identify when a different method is better.
Guidance for parents and educators
Ask “what stays true?” and “what could make this conclusion fail?” before asking for speed. Invite the student to draw the input and output, estimate the result and locate the first step that disagrees with a reference. These prompts reveal conceptual understanding more clearly than memorised terminology.
Advanced enrichment should sit beside secure school foundations in algebra, functions, geometry, statistics and computational thinking. It need not accelerate a student into a fixed career identity. A healthy goal is curiosity with discipline: the learner becomes comfortable reading unfamiliar notation, checking an example, revising a model and communicating uncertainty.
Evidence prompts for a useful conversation
- Which quantity is observed and which is inferred?
- Which step saves work, and why is it allowed?
- Is the claim exact, approximate, probabilistic or empirical?
- What units and conventions are in use?
- Which input makes the method struggle?
- What simple baseline could check the answer?
- What would count as evidence that the parameters are poor?
Mini-project assessment
A strong mini-project contains the original question, a small reproducible dataset, a hand-worked example, code or a spreadsheet trace, at least one boundary test, a comparison with a baseline, and a paragraph on limits. Assess the reasoning trail as well as the final output. Repairing a model after a surprising result is valuable mathematical progress.
Six evidence checks for a finished project
Check 1: Define all-pairs shortest paths
Ask the student to demonstrate how to define all-pairs shortest paths without relying on a hidden software step. The evidence should include a labelled input, the exact rule used, one intermediate state and a result that can be checked independently. If the answer changes after labels or order change, the student should say whether that reflects the mathematics or only a convention.
Then request one deliberately awkward example. The learner should predict the difficulty before running the method, explain what the output does and does not establish, and name a reasonable alternative or safeguard. This check joins correctness with judgement: a technically valid calculation is useful only when its assumptions and interpretation remain visible.
Check 2: Run bellman–ford preprocessing
Ask the student to demonstrate how to run Bellman–Ford preprocessing without relying on a hidden software step. The evidence should include a labelled input, the exact rule used, one intermediate state and a result that can be checked independently. If the answer changes after labels or order change, the student should say whether that reflects the mathematics or only a convention.
Then request one deliberately awkward example. The learner should predict the difficulty before running the method, explain what the output does and does not establish, and name a reasonable alternative or safeguard. This check joins correctness with judgement: a technically valid calculation is useful only when its assumptions and interpretation remain visible.
Check 3: Compute vertex potentials
Ask the student to demonstrate how to compute vertex potentials without relying on a hidden software step. The evidence should include a labelled input, the exact rule used, one intermediate state and a result that can be checked independently. If the answer changes after labels or order change, the student should say whether that reflects the mathematics or only a convention.
Then request one deliberately awkward example. The learner should predict the difficulty before running the method, explain what the output does and does not establish, and name a reasonable alternative or safeguard. This check joins correctness with judgement: a technically valid calculation is useful only when its assumptions and interpretation remain visible.
Check 4: Reweight an edge
Ask the student to demonstrate how to reweight an edge without relying on a hidden software step. The evidence should include a labelled input, the exact rule used, one intermediate state and a result that can be checked independently. If the answer changes after labels or order change, the student should say whether that reflects the mathematics or only a convention.
Then request one deliberately awkward example. The learner should predict the difficulty before running the method, explain what the output does and does not establish, and name a reasonable alternative or safeguard. This check joins correctness with judgement: a technically valid calculation is useful only when its assumptions and interpretation remain visible.
Check 5: Prove nonnegative transformed weights
Ask the student to demonstrate how to prove nonnegative transformed weights without relying on a hidden software step. The evidence should include a labelled input, the exact rule used, one intermediate state and a result that can be checked independently. If the answer changes after labels or order change, the student should say whether that reflects the mathematics or only a convention.
Then request one deliberately awkward example. The learner should predict the difficulty before running the method, explain what the output does and does not establish, and name a reasonable alternative or safeguard. This check joins correctness with judgement: a technically valid calculation is useful only when its assumptions and interpretation remain visible.
Check 6: Use telescoping sums
Ask the student to demonstrate how to use telescoping sums without relying on a hidden software step. The evidence should include a labelled input, the exact rule used, one intermediate state and a result that can be checked independently. If the answer changes after labels or order change, the student should say whether that reflects the mathematics or only a convention.
Then request one deliberately awkward example. The learner should predict the difficulty before running the method, explain what the output does and does not establish, and name a reasonable alternative or safeguard. This check joins correctness with judgement: a technically valid calculation is useful only when its assumptions and interpretation remain visible.
Frequently asked questions
What problem does Johnson’s algorithm solve?
All-pairs shortest paths in a sparse weighted directed graph.
May edges be negative?
Yes, provided no relevant negative cycle exists.
Why add a new source?
Zero edges let Bellman–Ford reach every vertex and compute potentials.
What is the reweighting formula?
w′(u,v)=w(u,v)+h(u)−h(v).
Why are new weights nonnegative?
Bellman–Ford shortest-path inequalities imply it.
Why do shortest paths stay the same?
Potential terms telescope to one endpoint-dependent offset.
How many Dijkstra runs are used?
One from each original vertex.
When is Floyd–Warshall preferable?
Often for dense or modest-sized graphs.
What happens with a negative cycle?
The preprocessing detects it and the standard algorithm stops.
What should students know first?
Directed graphs, shortest paths, inequalities, telescoping sums and priority queues.
Useful next reading and sources
Source: Donald B. Johnson’s 1977 Journal of the ACM paper on sparse-network shortest paths.
Source: NIST Dictionary of Algorithms and Data Structures entry for Johnson’s algorithm.
Related eduKateSG reading: Bellman–Ford relaxation and negative edges.
Related eduKateSG reading: Floyd–Warshall all-pairs distances.
Related eduKateSG reading: Eppstein sidetracks and k shortest paths.
Read sources with a question in mind: which definition, theorem, default or limitation is being supported? An authoritative link is useful evidence, but it does not replace a worked calculation or a clear statement of how the source applies to the example.
A cheerful final thought
Mathematics becomes friendlier when every symbol has a job and every claim has a boundary. Start small, make the state visible, test the awkward case, and celebrate the moment when a pattern becomes explainable. That is the practical benefit of learning mathematics: not certainty about every future, but a growing ability to ask better questions and build trustworthy answers.