![]() |
VOOZH | about |
Given a directed weighted graph, your task is to find whether the given graph contains any negative cycles that are reachable from the source vertex (e.g., node 0).
Note: A negative-weight cycle is a cycle in a graph whose edges sum to a negative value.
Examples:
Input: V = 4, edges[][] = [[0, 3, 6], [1, 0, 4], [1, 2, 6], [3, 1, 2]]
๐ Example1Output: 0
Explanation : Cycle 1 โ 0 โ 3 โ 1 has total weight 6 + 4 + 2 = 12, which is positive, so no negative weight cycle exists.Input : V = 4, edges[][] = [[1, 0, 4], [3, 1, -2], [1, 2, -6], [2, 3, 5]]
๐ Example2
Output: 1
Explanation : There is a cycle 1 โ 2 โ 3 โ 1 with total weight -3, which is negative, so a negative weight cycle exists.
The idea is to use the Bellman-Ford Algorithm where we relax all edges V-1 times to compute shortest paths. In a normal graph, distances stabilize after these iterations. If we can still relax any edge after that, it means the distance is continuously decreasing, which happens only when there is a negative weight cycle in the graph.
dist with all values as 0(u, v, wt)dist[u] + wt < dist[v], update dist[v]1 (negative cycle exists) 0true
Related articles: