-
Notifications
You must be signed in to change notification settings - Fork 231
Expand file tree
/
Copy pathNegativeWeightCycle.cpp
More file actions
32 lines (26 loc) · 941 Bytes
/
NegativeWeightCycle.cpp
File metadata and controls
32 lines (26 loc) · 941 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// https://practice.geeksforgeeks.org/problems/negative-weight-cycle3504/1
class Solution {
public:
int isNegativeWeightCycle(int n, vector<vector<int>>edges){
// Code here
vector<int> distance(n+1, 1e9);
distance[1]= 0;
for(int i=1; i<=n; i++){
for(int j=0; j<edges.size(); j++){
int first= edges[j][0];
int second= edges[j][1];
int weight= edges[j][2];
if(distance[first]!=1e9 && ((distance[first] + weight)<distance[second]))
distance[second]= distance[first] + weight;
}
}
for(int j=0; j<edges.size(); j++){
int first= edges[j][0];
int second= edges[j][1];
int weight= edges[j][2];
if(distance[j]!=1e9 && (distance[first] + weight)<distance[second])
return true;
}
return false;
}
};