October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk5 min

How to Detect and Prevent Negative Cycles in a Graph

A negative cycle makes affected shortest-path costs unbounded. Learn the right Bellman–Ford or Floyd–Warshall test, how to recover a cycle, and how to handle it safely.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

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.

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.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

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.

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.

  1. Initialize all distances to zero and record a predecessor for each vertex whenever a relaxation updates it.
  2. Run |V| full passes over the edges, remembering a vertex updated on the last pass.
  3. If no vertex changes on the last pass, this test found no negative cycle.
  4. If a vertex x changes on the last pass, follow predecessor links from x exactly |V| times. This moves into a cycle.
  5. 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.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

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.

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.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

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.

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

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.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.