Given a directed weighted graph, report a negative-weight cycle in the graph, if any. A negative-weight cycle is a cycle in a graph whose edges sum to a negative value.

For example, consider the following graph:

Negative-weight cycle

It has one negative-weight cycle, 1—2—3—1 with sum -2.

Practice this problem

Approach 1: Using Bellman–Ford algorithm

Bellman–Ford algorithm is used to compute the shortest paths from a single source vertex to all the other vertices in a given weighted digraph. It can be modified to report any negative-weight cycle in the graph.

To check if the graph contains a negative-weight cycle, run Bellman–Ford once from each vertex. After running the relaxation step in Bellman–Ford V-1 times, the idea is to perform a final scan of all the edges. If any distance is updated, then a path of length |V| edges have been found, which can only occur if at least one negative cycle exists in the graph.

The time complexity of this approach will be O(V2 × E), where V and E are the total number of vertices and edges in the graph, respectively. If the graph is dense, i.e., E = V2, then the time complexity becomes O(V4).

 
This is demonstrated below in C++, Java, and Python:

C++


Download  Run Code

Output:

Negative-weight cycle found

Java


Download  Run Code

Output:

Negative-weight cycle found

Python


Download  Run Code

Output:

Negative-weight cycle found

Approach 2: Using Floyd–Warshall Algorithm

Floyd–Warshall algorithm is an algorithm for finding the shortest paths in a weighted graph with positive or negative edge weights. It can easily be modified to report any negative-weight cycle in the graph.

To detect negative cycles using the Floyd–Warshall algorithm, check the cost matrix’s diagonal for any negative number as it indicates that the graph contains at least one negative cycle. The Floyd–Warshall algorithm iteratively revises path lengths between all pairs of vertices (i, j), including where i = j. Initially, the length of the path (i, i) is zero. A path [i, k…i] can only improve upon this if it has a length less than zero, i.e., denotes a negative cycle. Thus, (i, i) will be negative if there exists a negative-length path from i back to i. The time complexity of this approach is O(V3), where V is the total number of vertices in the graph.

 
This is demonstrated below in C++, Java, and Python:

C++


Download  Run Code

Output:

Negative-weight cycle found

Java


Download  Run Code

Output:

Negative-weight cycle found

Python


Download  Run Code

Output:

Negative-weight cycle found