Skip to content

Commit

Permalink
Create BellmanFordAlgo.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
kshitiz11101 authored Jul 1, 2024
1 parent 8fd0d0c commit b200b16
Showing 1 changed file with 38 additions and 0 deletions.
38 changes: 38 additions & 0 deletions Graphs/BellmanFordAlgo.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
// User function Template for C++

class Solution {
public:
/* Function to implement Bellman Ford
* edges: vector of vectors which represents the graph
* S: source vertex to start traversing graph with
* V: number of vertices
*/
vector<int> bellman_ford(int V, vector<vector<int>>& edges, int S) {
// Code here
vector<int>dist(V,1e8);
dist[S]=0;
for(int i=0;i<V-1;i++){
for(auto it:edges){
int u=it[0];
int v=it[1];
int wt=it[2];

if(dist[u]!=1e8 && dist[u]+wt<dist[v]){
dist[v]=dist[u]+wt;
}
}
}
// Nth Relaxation
for(auto it:edges){
int u=it[0];
int v=it[1];
int wt=it[2];
if(dist[u]!=1e8 && dist[u]+wt<dist[v]){
return {-1};
}
}


return dist;
}
};

0 comments on commit b200b16

Please sign in to comment.