Skip to content

Commit d72a548

Browse files
authored
Create Bellman-Ford Algorithm
1 parent 9010481 commit d72a548

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

Graphs/Bellman-Ford Algorithm

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
class Solution {
2+
// Function to implement Bellman Ford
3+
// edges: array of arrays which represents the graph
4+
// S: source vertex to start traversing graph with
5+
// V: number of vertices
6+
bellmanFord(V, edges, S) {
7+
// Initialize distance array with a large value (1e8)
8+
let dis = new Array(V).fill(1e8);
9+
dis[S] = 0;
10+
11+
// Bellman Ford algorithm
12+
for (let i = 0; i < V - 1; i++) {
13+
for (let edge of edges) {
14+
let u = edge[0];
15+
let v = edge[1];
16+
let wt = edge[2];
17+
18+
// If you have not reached 'u' till now, move forward
19+
if (dis[u] !== 1e8 && dis[u] + wt < dis[v]) {
20+
// Update distance array
21+
dis[v] = dis[u] + wt;
22+
}
23+
}
24+
}
25+
26+
// Checking for negative cycle
27+
// Check for nth relaxation
28+
for (let edge of edges) {
29+
let u = edge[0];
30+
let v = edge[1];
31+
let wt = edge[2];
32+
33+
if (dis[u] !== 1e8 && dis[u] + wt < dis[v]) {
34+
// If the distance array gets reduced for the nth iteration
35+
// It means a negative cycle exists
36+
return [-1];
37+
}
38+
}
39+
40+
return dis;
41+
}
42+
}
43+
44+
// Example usage:
45+
let solution = new Solution();
46+
let V = 5; // Number of vertices
47+
let edges = [
48+
[0, 1, -1],
49+
[0, 2, 4],
50+
[1, 2, 3],
51+
[1, 3, 2],
52+
[1, 4, 2],
53+
[3, 2, 5],
54+
[3, 1, 1],
55+
[4, 3, -3]
56+
];
57+
let S = 0; // Source vertex
58+
59+
console.log(solution.bellmanFord(V, edges, S));

0 commit comments

Comments
 (0)