VOOZH about

URL: https://www.geeksforgeeks.org/dsa/print-negative-weight-cycle-in-a-directed-graph/

⇱ Print negative weight cycle in a Directed Graph - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Print negative weight cycle in a Directed Graph

Last Updated : 15 Jul, 2025

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 

👁 Image


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: 
 

👁 Image


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: 

  • Perform N-1 iterations of Bellman-Ford algorithm and relax each edge (u, v). Keep track of parent of each vertex and store in an array parent[].
  • Now, do one more iteration and if no edge relaxation take place in this Nth iteration, then there is no cycle of negative weight exists in the graph.
  • Otherwise take a variable C and store the vertex v from any edge (u, v), which is relaxed in the Nth iteration.
  • Now, starting from the C vertex go towards its ancestors until a cycle is found and finally print it.
  • This cycle will be the desired cycle of negative weight.

Below is the implementation of the above approach: 


Output: 
1 2 3 4 1

 

Time Complexity: O(V*E) 
Auxiliary Space: O(V)
 

Comment