Skip to content

Commit e0df43d

Browse files
Added Bellmen_Ford Algorithm
Updated the file
1 parent 9955e65 commit e0df43d

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
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. */

0 commit comments

Comments
 (0)