Negative weight cycle | Practice | GeeksforGeeks

Given a weighted directed graph with n nodes and m edges. Nodes are labeled from 0 to n-1, the task is to check if it contains a negative weight cycle or not.
Note: edges[i] is defined as u, v and weight.
 
Example 1:
Input: n = 3, edges = {{0,1,-1},{1,2,-2},
{2,0,-3}}
Output: 1
Explanation: The graph contains negative weight
cycle as 0->1->2->0 with weight -1,-2,-3.

Example 2:
Input: n = 3, edges = {{0,1,-1},{1,2,-2},
{2,0,3}}
Output: 0
Explanation: The graph does not contain any
negative weight cycle.

 
Your Task:
You don't need to read or print anyhting. Your task is to complete the function isNegativeWeightCycle() which takes n and edges as input paramater and returns 1 if graph contains negative weight cycle otherwise returns 0.
 
Expected Time Complexity: O(n*m)
Expected Space Compelxity: O(n)
 
Constraints:
1 <= n <= 100
1 <= m <= n*(n-1), where m is the total number of Edges in the directed graph.
0
roboto7o32oo33 days ago
Clean Python Solution ✨ ✨ (Using Bellman Ford's Algorithm)
 
class Solution:
	def isNegativeWeightCycle(self, n, edges):
	    
	    # initialize all the distance to be infinite
	    distance = [float('inf') for _ in range(n)]
	    
	    # make distance to vertex 0 to be 0
	    distance[0] = 0
	    
	    # iterate over all the edges n-1 times
	    for _ in range(n-1):
	        for (u,v,w) in edges:
	            distance[v] = min(distance[v], distance[u]+w)
	    
	    # check if distance has converged after n-1 iterations, if not then there is a negative cycle
	    for (u,v,w) in edges:
	        if distance[v] > distance[u]+w:
	            return 1
	   
	    return 0
0
donkn69123 days ago
	int isNegativeWeightCycle(int n, vector<vector<int>>edges){
	    int m = edges.size();
    int inf = 10000000; 
    vector<int> dist(n, inf); 
    dist[0] = 0; 
    for(int j = 0; j<n-1; j++){
    for(int i = 0;i<m;i++) {
            if(dist[edges[i][0]] + edges[i][2] < dist[edges[i][1]]) {
                dist[edges[i][1]] = dist[edges[i][0]] + edges[i][2]; 
            }
    }
    } 
    //relaxing n-1 times according to Bellman Ford

    // int fl = 0; 
    for(int i = 0;i<m;i++) {
            if(dist[edges[i][0]] + edges[i][2] < dist[edges[i][1]]) {
               return 1;
            }
    }
    //if relaxing nth time gives less distance then there is a negative cycle.
            
        
    
    
    return 0;
	}
0
yashwant19je09383 days ago
Don't Know what the heck happened but, I just make one change in cycle detection code i.e.,  (in checks include) if weight is negative, return true :)) ... and all test cases passed.
+1
akshaydayma93512 weeks ago
 
It can be solved just by using dfs. 
→Call dfs n(number of vertices) times.
→In dfs, while traversing if you encounter cycle and it's summation of weight comes out to be negative. Then just return graph contains negative cycle. 
 
 
struct Node{       int data;       int weight;   };      void edge(vector<vector<Node> > &adj, int a, int b, int w){       Node temp2;              temp2.data = b;       temp2.weight = w;              adj[a].push_back(temp2); //directed graph given   }      int dfs(int node, vector<vector<Node> > &adj, vector<bool> &visited, int sum){       visited[node] = true;
       for(int i=0;i<adj[node].size();i++){           if(!visited[adj[node][i].data]){               if(dfs(adj[node][i].data,adj, visited,sum+adj[node][i].weight) == 1) return 1;           }           else{               if( sum+adj[node][i].weight < 0 )                   return 1;           }       }       visited[node] = false;       return 0;   }
int isNegativeWeightCycle(int n, vector<vector<int>>edges){    // Code here    vector<vector<Node> > adj(n);    for(int i=0;i<edges.size();i++){        edge(adj, edges[i][0], edges[i][1], edges[i][2]);    }        vector<bool> visited(n, false);        for(int i=0;i<n;i++){        if(!visited[i]){            if(dfs(i, adj, visited, 0) == 1) return 1;         }    }        return 0;}
+3
learningdsa2 weeks ago
Concise Bellman Ford's Algorithm (C++): [0.85/2.8]
int isNegativeWeightCycle(int n, vector<vector<int>>edges){
	vector<int> distance(n, INT_MAX);
	distance[0] = 0;
	for(int x = 0; x < n - 1; x++){
	   for(auto z: edges){
	      if(distance[z[0]] != INT_MAX and distance[z[1]] > distance[z[0]] + z[2]){
	           distance[z[1]] = distance[z[0]] + z[2];
	        }
	    }
	}
    for(auto z: edges){
        if(distance[z[0]] != INT_MAX and distance[z[1]] > distance[z[0]] + z[2]){
           return 1;
        }
    }
	return 0;
}
+7
ashishkyjp113 weeks ago
Don't use INT_MAX as an initializer in the distance array, as it will throw some error. Use some other value like 1e+6.
0
ashishkyjp113 weeks ago
int isNegativeWeightCycle(int n, vector<vector<int>>edges){
	    // Code here
	    vector<int> dist(n,1000000);
	    dist[0]=0;
	    
	    for(int i=1; i<=n-1; i++)
	    {
            for(auto &edge:edges)
	        {
	            if(dist[edge[0]]+edge[2]<dist[edge[1]])
	            {
	                dist[edge[1]]=dist[edge[0]]+edge[2];
	            }
	        }
	    }
	    
        for(auto &edge:edges)
        {
            if(dist[edge[0]]+edge[2]<dist[edge[1]])
            {
               return 1;
            }
        }
	    
	    return 0;
	}
0
monilmodi2002
This comment was deleted.
0
vishaltalawar034 weeks ago
class Solution{   public int isNegativeWeightCycle(int n, int[][] edges)   {       //code here       int dist[] = new int[n];       Arrays.fill(dist, Integer.MAX_VALUE);       dist[0] = 0;              for(int count = 1;count<n; count++){           for(int j=0;j<edges.length;j++){               int src = edges[j][0];               int dest = edges[j][1];               int wt = edges[j][2];               if(dist[src]!=Integer.MAX_VALUE && dist[src] + wt < dist[dest]){                   dist[dest] = dist[src] +wt;                                  }           }       }       for(int j=0;j<edges.length;j++){               int src = edges[j][0];               int dest = edges[j][1];               int wt = edges[j][2];               if(dist[src]!=Integer.MAX_VALUE && dist[src] + wt < dist[dest]){                   return 1;                                  }       }       return 0;              }}
0
kurmiamreet444 weeks ago
class Solution{   public int isNegativeWeightCycle(int n, int[][] edges)   {       int [] visited = new int[n];// stores the minimum cost value for each vertex from the source       Arrays.fill(visited, Integer.MAX_VALUE);       visited[0]=0;                     for(int i=0;i<n-1;i++)// iteration for n vertices to check negative weight       // if in the final i.e more than n-1 runs and  the visited array value changes then it is negative weight cycle       // it takes n-1 runs to completely work on the graph in Bellman Ford algorithm       {          for(int j=0;j<edges.length;j++)//cycle through the 2d graph             {                if(visited[edges[j][0]]!= Integer.MAX_VALUE &&visited[edges[j][0]]+edges[j][2]<visited[edges[j][1]])              {                  visited[edges[j][1]]=visited[edges[j][0]] +edges[j][2];              }            }       }               for(int j=0;j<edges.length;j++)            {                if(visited[edges[j][0]]+edges[j][2]<visited[edges[j][1]])              {                  return 1;              }            }       return 0;   }}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested 
                                    against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code.
                                    On submission, your code is tested against multiple test cases consisting of all
                                        possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as
                                        the final solution code.
You can view the solutions submitted by other users from the submission tab.
Make sure you are not using ad-blockers.
Disable browser extensions.
We recommend using latest version of your browser for best experience.
Avoid using static/global variables in coding problems as your code is tested 
                                against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases in coding problems does not guarantee the 
                                correctness of code. On submission, your code is tested against multiple test cases
                                    consisting of all possible corner cases and stress constraints.