-
-
Notifications
You must be signed in to change notification settings - Fork 5.8k
Expand file tree
/
Copy pathBellmanFordNegativeCycle.js
More file actions
31 lines (25 loc) · 833 Bytes
/
BellmanFordNegativeCycle.js
File metadata and controls
31 lines (25 loc) · 833 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
/*
* Author: Mayank
* Bellman-Ford Algorithm implementation in JavaScript
* Detects shortest paths and checks for negative weight cycles in a graph.
*/
// Bellman-Ford with negative cycle detection
function bellmanFordNegativeCycle(graph, vertices, start) {
const dist = new Array(vertices).fill(Infinity)
dist[start] = 0
for (let i = 0; i < vertices - 1; i++) {
for (const [u, v, w] of graph) {
if (dist[u] !== Infinity && dist[u] + w < dist[v]) {
dist[v] = dist[u] + w
}
}
}
for (const [u, v, w] of graph) {
if (dist[u] !== Infinity && dist[u] + w < dist[v]) {
// A shorter path found after V-1 iterations means a negative cycle exists
return { hasNegativeCycle: true, dist }
}
}
return { hasNegativeCycle: false, dist }
}
export { bellmanFordNegativeCycle }