Use Bellman–Ford to test for a negative cycle reachable from a chosen source, or initialize every vertex at distance zero to test the whole graph. For all-pairs distances, Floyd–Warshall detects a cycle when a final diagonal entry is negative. Preventing cycles is different: validate how your application assigns edge weights and decide what it should do when a cycle makes a shortest-path result unbounded.
What a negative cycle means
A negative cycle is a directed cycle whose edge weights sum to less than zero. Each time a path traverses it, its total cost falls. If a source can reach the cycle and the cycle can reach a target, that source-to-target cost can be made arbitrarily small by looping more times; there is no finite shortest-path distance for that pair.
| # | Preview | Product | Price | |
|---|---|---|---|---|
| 1 |
|
Introduction to Graph Theory (Dover Books on Mathematics) | $15.09 | Buy on Amazon |
| 2 |
|
Graph Theory (Graduate Texts in Mathematics, 173) | $45.75 | Buy on Amazon |
| 3 |
|
A First Course in Graph Theory (Dover Books on Mathematics) | $24.41 | Buy on Amazon |
| 4 |
|
Basic Graph Theory | $40.00 | Buy on Amazon |
| 5 |
|
The Fascinating World of Graph Theory | $15.97 | Buy on Amazon |
As an Amazon Associate I earn from qualifying purchases.
A negative edge alone is not a negative cycle. The issue is whether a cycle’s total weight is negative, and whether that cycle is reachable within the query being answered.
Detect a cycle reachable from one source with Bellman–Ford
For source vertex s, set its distance to zero and all other distances to infinity. Relax every edge up to |V| − 1 times. If a further pass can still relax an edge whose start vertex has a finite distance, a negative cycle is reachable from s. Bellman–Ford takes O(VE) time; the University of Texas at Austin’s companion material describes the additional-pass test and its Bellman–Ford analysis.
#1 Best Overall
The test’s scope matters: it does not find a negative cycle in a disconnected component that the source cannot reach. A shortest path without a reachable negative cycle can be represented without repeated vertices, so it uses at most |V| − 1 edges.
Detect a negative cycle anywhere in the graph
To test the entire graph, make every vertex reachable for the test. One equivalent approach is to add a temporary super-source with a zero-weight edge to every vertex. Another is to initialize every vertex’s distance to zero, which has the same effect. Run Bellman–Ford for |V| passes: if an edge can still be relaxed on the last pass, a negative cycle exists somewhere. CP-Algorithms documents this method and cycle recovery with predecessor links; NetworkX uses a temporary node connected to every node in its graph-wide detector.
Rank #2
- Initialize all distances to zero and record a predecessor for each vertex whenever a relaxation updates it.
- Run
|V|full passes over the edges, remembering a vertex updated on the last pass. - If no vertex changes on the last pass, this test found no negative cycle.
- If a vertex
xchanges on the last pass, follow predecessor links fromxexactly|V|times. This moves into a cycle. - Continue following predecessors until a vertex repeats; the repeated segment gives a cycle witness. Reverse the order if you need to list its edges in forward traversal order.
Without predecessor tracking, the last-pass test still answers yes or no, but it cannot provide a cycle witness. The distinction between a source-reachable check and a graph-wide check is important in code as well as in prose.
The Tool Desk
Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →Use Floyd–Warshall for all-pairs detection
Floyd–Warshall computes shortest-path distances between every pair by successively allowing each vertex as an intermediate point. After the algorithm, a negative diagonal entry d[t][t] < 0 signals a negative-weight closed walk and therefore a negative cycle. The standard algorithm takes O(V³) time and O(V²) space.
A negative diagonal identifies a cycle, but it does not mean every pair is affected. A pair (i, j) has no finite shortest-path distance if i can reach a negative cycle and that cycle can reach j. CP-Algorithms explains negative-cycle detection and affected-pair propagation. The algorithm’s all-pairs cost makes it a natural straightforward choice for dense graphs, while sparse graphs may favor Johnson’s algorithm when no negative cycle exists.
Choose an algorithm for the question
| Need | Approach | Scope and cost |
|---|---|---|
| Shortest paths from one source, with negative edges possible | Bellman–Ford | O(VE); detects cycles reachable from that source. |
| Check for a cycle anywhere, optionally returning a witness | Bellman–Ford with all-zero initialization or a super-source | O(VE); predecessor links can recover a cycle. |
| All-pairs distances on a dense graph | Floyd–Warshall | O(V³) time and O(V²) space. |
| All-pairs distances on a sparse graph with negative edges but no negative cycle | Johnson | Suitable for sparse all-pairs work; Boost lists O(VE + V² log V). |
NetworkX’s shortest-path reference lists Bellman–Ford at O(VE), Floyd–Warshall at O(V³), and Johnson at O(V(V + E) log V). Boost gives the Johnson bound as O(VE + V² log V). These are published algorithmic complexity bounds, not measured runtimes; actual performance depends on graph structure and implementation.
Rank #4
Johnson’s method combines Bellman–Ford and Dijkstra after reweighting, and is not a workaround for a negative cycle: the graph must have none. For library-specific query support and complexity details, consult the NetworkX shortest-path reference and Boost.Graph shortest-path documentation.
Free tools Windows power users keep installed
One-click scans. No signup required.
Prevent bad results with validation and an explicit policy
There is no universal weight adjustment that removes negative cycles while preserving the meaning of arbitrary edge weights. Prevention therefore starts with the model and the input pipeline—not with silently changing the graph.
Best Value
- Validate weight inputs, units, and sign conventions before building the graph. Check that a negative value is intentional rather than a parsing or unit-conversion error.
- If the application promises finite shortest paths, run a negative-cycle check with the scope that matches the query before treating distances as answers.
- Decide what the application should report when a cycle is found: reject the input, identify the cycle or affected vertices and pairs, or return an explicit unbounded result.
- Do not clamp weights, delete edges, or shift every weight without a domain-based reason and a proof that the change preserves the path comparisons and cycle meaning your application needs.
The right policy depends on the application. A cycle may indicate corrupt data, or it may be a valid feature of the model; the detection algorithm establishes the graph property, not what the product should do about it.
Implementation checks that prevent false results
- In source-rooted Bellman–Ford, only relax an edge if its start vertex has a finite distance. Otherwise an infinity sentinel can accidentally be combined with a weight.
- Use a numeric type wide enough for accumulated path weights. Guard against overflow, and choose an infinity representation that cannot be mistaken for a real distance.
- Preserve predecessor links during relaxations if callers need an explanation cycle, not just a Boolean result.
- Make the test’s scope explicit in the function name, API, or output: “reachable from source” and “anywhere in the graph” are different guarantees.
NetworkX 3.7 documents negative_edge_cycle as a graph-wide Boolean check. Its API describes a heuristic option that may enable earlier detection, and claims at least an order-of-magnitude performance increase when a negative cycle exists; that is the library’s documentation claim, not an independent benchmark. The API’s documented Boolean result is summarized as “True if a negative edge cycle exists, otherwise False.” See the NetworkX negative_edge_cycle API.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.




