Skip to content

Create Bellman-Ford Algorithm #1692

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 59 additions & 0 deletions Graphs/Bellman-Ford Algorithm
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
class Solution {
// Function to implement Bellman Ford
// edges: array of arrays which represents the graph
// S: source vertex to start traversing graph with
// V: number of vertices
bellmanFord(V, edges, S) {
// Initialize distance array with a large value (1e8)
let dis = new Array(V).fill(1e8);
dis[S] = 0;

// Bellman Ford algorithm
for (let i = 0; i < V - 1; i++) {
for (let edge of edges) {
let u = edge[0];
let v = edge[1];
let wt = edge[2];

// If you have not reached 'u' till now, move forward
if (dis[u] !== 1e8 && dis[u] + wt < dis[v]) {
// Update distance array
dis[v] = dis[u] + wt;
}
}
}

// Checking for negative cycle
// Check for nth relaxation
for (let edge of edges) {
let u = edge[0];
let v = edge[1];
let wt = edge[2];

if (dis[u] !== 1e8 && dis[u] + wt < dis[v]) {
// If the distance array gets reduced for the nth iteration
// It means a negative cycle exists
return [-1];
}
}

return dis;
}
}

// Example usage:
let solution = new Solution();
let V = 5; // Number of vertices
let edges = [
[0, 1, -1],
[0, 2, 4],
[1, 2, 3],
[1, 3, 2],
[1, 4, 2],
[3, 2, 5],
[3, 1, 1],
[4, 3, -3]
];
let S = 0; // Source vertex

console.log(solution.bellmanFord(V, edges, S));