We are given a directed graph. We need compute whether the graph has negative cycle or not. A negative cycle is one in which the overall sum of the cycle comes negative.
Negative weights are found in various applications of graphs. For example, instead of paying cost for a path, we may get some advantage if we follow the path.
Input : 4 4 0 1 1 1 2 -1 2 3 -1 3 0 -1 Output : Yes The graph contains a negative cycle.
We have discussed Bellman Ford Algorithm based solution for this problem.
In this post, Floyd Warshall Algorithm based solution is discussed that works for both connected and disconnected graphs.
Distance of any node from itself is always zero. But in some cases, as in this example, when we traverse further from 4 to 1, the distance comes out to be -2, i.e. distance of 1 from 1 will become -2. This is our catch, we just have to check the nodes distance from itself and if it comes out to be negative, we will detect the required negative cycle.
This article is contributed by Shivani Mittal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Floyd Warshall Algorithm | DP-16
- Comparison of Dijkstra’s and Floyd–Warshall algorithms
- Finding shortest path between any two nodes using Floyd Warshall Algorithm
- Print negative weight cycle in a Directed Graph
- Detect a negative cycle in a Graph | (Bellman Ford)
- How does Floyd's slow and fast pointers approach work?
- Coloring a Cycle Graph
- Number of Hamiltonian cycle
- Hamiltonian Cycle | Backtracking-6
- Degree of a Cycle Graph
- Detect cycle in an undirected graph using BFS
- Detect cycle in an undirected graph
- Detect Cycle in a Directed Graph using BFS
- Detect Cycle in a Directed Graph
- Check if a graphs has a cycle of odd length
- Count of all cycles without any inner cycle in a given Graph
- Proof that Hamiltonian Cycle is NP-Complete
- Check if there is a cycle with odd weight sum in an undirected graph
- Detect Cycle in a directed graph using colors
- Shortest cycle in an undirected unweighted graph