Skip to content

Commit 70c5e05

Browse files
Merge pull request #62 from sourav-naskar/main
added Bellman-Ford Algorithm
2 parents 257dfc5 + 8c868df commit 70c5e05

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
#include<bits/stdc++.h>
2+
using namespace std;
3+
struct node {
4+
int u;
5+
int v;
6+
int wt;
7+
node(int first, int second, int weight) {
8+
u = first;
9+
v = second;
10+
wt = weight;
11+
}
12+
};
13+
14+
int main(){
15+
int N=6,m=7;
16+
vector<node> edges;
17+
edges.push_back(node(0,1,5));
18+
edges.push_back(node(1,2,-2));
19+
edges.push_back(node(1,5,-3));
20+
edges.push_back(node(2,4,3));
21+
edges.push_back(node(3,2,6));
22+
edges.push_back(node(3,4,-2));
23+
edges.push_back(node(5,3,1));
24+
int src=0;
25+
int inf = 10000000;
26+
vector<int> dist(N, inf);
27+
dist[src] = 0;
28+
for(int i = 1;i<=N-1;i++) {
29+
for(auto it: edges) {
30+
if(dist[it.u] + it.wt < dist[it.v]) {
31+
dist[it.v] = dist[it.u] + it.wt;
32+
}
33+
}
34+
}
35+
36+
int fl = 0;
37+
for(auto it: edges) {
38+
if(dist[it.u] + it.wt < dist[it.v]) {
39+
cout << -1;
40+
fl = 1;
41+
break;
42+
}
43+
}
44+
45+
if(!fl) {
46+
for(int i = 0;i<N;i++) {
47+
cout << dist[i]<<" ";
48+
}
49+
}
50+
return 0;
51+
}
52+
53+
/*
54+
Output:
55+
0 5 3 3 1 2
56+
57+
Time Complexity: O(N*E). We check E edges N times
58+
59+
Space Complexity: O(N). Distance Array
60+
*/
61+
62+
//contributed by Sourav Naskar

0 commit comments

Comments
 (0)