diff --git a/Graph_Algorithms/src/Bellmen_Ford_Algorithm/Bellmen_Ford.cpp b/Graph_Algorithms/src/Bellmen_Ford_Algorithm/Bellmen_Ford.cpp new file mode 100644 index 00000000..1bae9bdf --- /dev/null +++ b/Graph_Algorithms/src/Bellmen_Ford_Algorithm/Bellmen_Ford.cpp @@ -0,0 +1,65 @@ +//Bellmen Ford algorithm to detect negative weight cycle +//Time Complexity is O(V*E) +//Space Complexity is O(V) + +#include +using namespace std; +#define inf INT_MAX + +int main() +{ + int v,e; //V=total vertices e=total edges + cin>>v>>e; + vector>edges; + for(int i=0;i>x>>y>>w; + edges.push_back({x,y,w}); + } + + //dis will store the minimum weight of that vertex + int dis[v]={inf}; + dis[0]=0; + + for(int i=1;i dis[x]+wt) + dis[y]=dis[x]+wt; + } + } + + + int flag=0; + for(int j=0;j dis[x]+wt) + { + dis[y]=dis[x]+wt; + flag=1; + } + } + + // If flag becomes 1 it means weight of vertex is still decreasing Hence is negative weight cycle + if(flag) + cout<<"Yes, this graph has negative weight cycle."; + else + cout<<"No, this graph doesn't have negative weight cycle."; + + return 0; + +} + + +/*Description +If we iterate through all edges v-1 times then it guarantees the shortest distance of vettices. +If we again iterate through all edges one more time and get a shorter path for any vertex, +then there is a negative weight cycle. */