-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbellmanFordAlgoGraph.cpp
More file actions
33 lines (33 loc) · 979 Bytes
/
bellmanFordAlgoGraph.cpp
File metadata and controls
33 lines (33 loc) · 979 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
33
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] = wt+dist[u];
}
}
}
// nth relaxation to check negative cycle
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;
}
};