![]() |
VOOZH | about |
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".
Input: V = 5, E = 5, Below is the graph:
Here, for the given negative cycle o/p (1->2->3->4->1) ; In fig there has to be Edge from 4-->1 not from 4-->0
Output: 1 2 3 4 1
Explanation:
Given graph contains a negative cycle, (1->2->3->4->1)Input: V = 5, E = 5, Below is the graph:
Output: 0 1 2 3 4 0
Explanation:
Given graph contains a negative cycle, (0->1->2->3->4->0)
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:
Below is the implementation of the above approach:
1 2 3 4 1
Time Complexity: O(V*E)
Auxiliary Space: O(V)