Detect a negative cycle in a Graph | (Bellman Ford)
We are given a directed graph. We need to compute whether the graph has a negative cycle or not. A negative cycle is one in which the overall sum of the cycle becomes 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.
The idea is to use Bellman-Ford Algorithm.
Below is an algorithm to find if there is a negative weight cycle reachable from the given source.
1) Initialize distances from the source to all vertices as infinite and distance to the source itself as 0. Create an array dist of size |V| with all values as infinite except dist[src] where src is the source vertex.
2) This step calculates the shortest distances. Do the following |V|-1 times where |V| is the number of vertices in the given graph.
a) Do the following for each edge u-v.
b) If dist[v] > dist[u] + weight of edge uv, then update dist[v].
c) dist[v] = dist[u] + weight of edge uv.
3) This step reports if there is a negative weight cycle in the graph. Do the following for each edge u-v
a) If dist[v] > dist[u] + weight of edge uv, then the “Graph has a negative weight cycle”
The idea of step 3 is, step 2 guarantees the shortest distances if the graph doesn’t contain a negative weight cycle. If we iterate through all edges one more time and get a shorter path for any vertex, then there is a negative weight cycle.
How does it work?
As discussed, the Bellman-Ford algorithm, for a given source, first calculates the shortest distances which have at most one edge in the path. Then, it calculates the shortest paths with at-most 2 edges, and so on. After the i-th iteration of the outer loop, the shortest paths with at most i edges are calculated. There can be a maximum |V| – 1 edge on any simple path, that is why the outer loop runs |v| – 1 time. If there is a negative weight cycle, then one more iteration would give a short route.
How to handle a disconnected graph (If the cycle is not reachable from the source)?
The above algorithm and program might not work if the given graph is disconnected. It works when all vertices are reachable from source vertex 0.
To handle disconnected graphs, we can repeat the process for vertices for which distance is infinite.
This article is contributed by kartik. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to email@example.com. 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.