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.
- Floyd Warshall Algorithm | DP-16
- Comparison of Dijkstra’s and Floyd–Warshall algorithms
- Detect a negative cycle in a Graph | (Bellman Ford)
- How does Floyd's slow and fast pointers approach work?
- Number of Hamiltonian cycle
- Hamiltonian Cycle | Backtracking-6
- Degree of a Cycle Graph
- Coloring a Cycle Graph
- Detect Cycle in a Directed Graph using BFS
- Detect cycle in an undirected graph using BFS
- Check if a graphs has a cycle of odd length
- Detect Cycle in a Directed Graph
- Detect cycle in an undirected graph
- Shortest cycle in an undirected unweighted graph
- Detect Cycle in a directed graph using colors