Given a weighted directed graph consisting of V vertices and E edges. The task is to print the cyclic path whose sum of weight is negative. If there is no such path present then print “-1”.
Approach: The idea is to use Bellman-Ford Algorithm which is used to detect a negative cycle or not. To print the negative cycles, perform the Nth iteration of Bellman-Ford and pick a vertex from any edge which is relaxed in this iteration. Using this vertex and its ancestors, the negative cycle can be printed. Below are the steps:
- Perform N-1 iterations of Bellman-Ford algorithm and relax each edge (u, v). Keep track of parent of each vertex and store in an array parent.
- Now, do one more iteration and if no edge relaxation take place in this Nth iteration, then there is no cycle of negative weight exists in the graph.
- Otherwise take a variable C and store the vertex v from any edge (u, v), which is relaxed in the Nth iteration.
- Now, starting from the C vertex go towards its ancestors until a cycle is found and finally print it.
- This cycle will be the desired cycle of negative weight.
Below is the implementation of the above approach:
1 2 3 4 1
Time Complexity: O(V*E)
Auxiliary Space: O(V)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Print Nodes which are not part of any cycle in a Directed Graph
- Detect Cycle in a Directed Graph
- Detect Cycle in a directed graph using colors
- Detect Cycle in a Directed Graph using BFS
- Detect cycle in Directed Graph using Topological Sort
- Find minimum weight cycle in an undirected graph
- Check if there is a cycle with odd weight sum in an undirected graph
- Detect a negative cycle in a Graph | (Bellman Ford)
- Detect a negative cycle in a Graph using Shortest Path Faster Algorithm
- Choose maximum weight with given weight and value ratio
- Count number of paths whose weight is exactly X and has at-least one edge of weight M
- Convert the undirected graph into directed graph such that there is no path of length greater than 1
- Convert undirected connected graph to strongly connected directed graph
- Karp's minimum mean (or average) weight cycle algorithm
- Detect cycle in the graph using degrees of nodes of graph
- Detecting negative cycle using Floyd Warshall
- Find if there is a path between two vertices in a directed graph
- Shortest Path in Directed Acyclic Graph
- Longest Path in a Directed Acyclic Graph
- Euler Circuit in a Directed Graph
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.