File tree Expand file tree Collapse file tree 1 file changed +65
-0
lines changed
Graph_Algorithms/src/Bellmen_Ford_Algorithm Expand file tree Collapse file tree 1 file changed +65
-0
lines changed Original file line number Diff line number Diff line change 1+ // Bellmen Ford algorithm to detect negative weight cycle
2+ // Time Complexity is O(V*E)
3+ // Space Complexity is O(V)
4+
5+ #include < bits/stdc++.h>
6+ using namespace std ;
7+ #define inf INT_MAX
8+
9+ int main ()
10+ {
11+ int v,e; // V=total vertices e=total edges
12+ cin>>v>>e;
13+ vector<vector<int >>edges;
14+ for (int i=0 ;i<e;i++)
15+ {
16+ int x,y,w;
17+ cin>>x>>y>>w;
18+ edges.push_back ({x,y,w});
19+ }
20+
21+ // dis will store the minimum weight of that vertex
22+ int dis[v]={inf};
23+ dis[0 ]=0 ;
24+
25+ for (int i=1 ;i<v;i++)
26+ {
27+ for (int j=0 ;j<e;j++)
28+ {
29+ int x=edges[j][0 ];
30+ int y=edges[j][1 ];
31+ int wt=edges[j][2 ];
32+ if (dis[y] > dis[x]+wt)
33+ dis[y]=dis[x]+wt;
34+ }
35+ }
36+
37+
38+ int flag=0 ;
39+ for (int j=0 ;j<e;j++)
40+ {
41+ int x=edges[j][0 ];
42+ int y=edges[j][1 ];
43+ int wt=edges[j][2 ];
44+ if (dis[y] > dis[x]+wt)
45+ {
46+ dis[y]=dis[x]+wt;
47+ flag=1 ;
48+ }
49+ }
50+
51+ // If flag becomes 1 it means weight of vertex is still decreasing Hence is negative weight cycle
52+ if (flag)
53+ cout<<" Yes, this graph has negative weight cycle." ;
54+ else
55+ cout<<" No, this graph doesn't have negative weight cycle." ;
56+
57+ return 0 ;
58+
59+ }
60+
61+
62+ /* Description
63+ If we iterate through all edges v-1 times then it guarantees the shortest distance of vettices.
64+ If we again iterate through all edges one more time and get a shorter path for any vertex,
65+ then there is a negative weight cycle. */
You can’t perform that action at this time.
0 commit comments