Skip to content

Commit f6ac7a8

Browse files
committed
Added Bellman Ford Negative Cycle implementation and test file with prettier code
1 parent 64137f5 commit f6ac7a8

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed

Graphs/BellmanFordNegativeCycle.js

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/*
2+
* Author: Mayank
3+
* Bellman-Ford Algorithm implementation in JavaScript
4+
* Detects shortest paths and checks for negative weight cycles in a graph.
5+
*/
6+
7+
// Bellman-Ford with negative cycle detection
8+
9+
function bellmanFordNegativeCycle(graph, vertices, start) {
10+
const dist = new Array(vertices).fill(Infinity)
11+
dist[start] = 0
12+
13+
// relax all edges (V - 1) times
14+
for (let i = 0; i < vertices - 1; i++) {
15+
for (let [u, v, w] of graph) {
16+
if (dist[u] !== Infinity && dist[u] + w < dist[v]) {
17+
dist[v] = dist[u] + w
18+
}
19+
}
20+
}
21+
22+
// check for negative cycle
23+
for (let [u, v, w] of graph) {
24+
if (dist[u] !== Infinity && dist[u] + w < dist[v]) {
25+
return { hasNegativeCycle: true, dist }
26+
}
27+
}
28+
29+
return { hasNegativeCycle: false, dist }
30+
}
31+
32+
export { bellmanFordNegativeCycle }
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/*
2+
* Test file for Bellman-Ford Negative Cycle Detection
3+
*/
4+
5+
import { bellmanFordNegativeCycle } from '../BellmanFordNegativeCycle.js'
6+
7+
test('should find shortest distance without negative cycle', () => {
8+
const graph = [
9+
[0, 1, 4],
10+
[0, 2, 5],
11+
[1, 2, -3],
12+
[2, 3, 4]
13+
]
14+
const result = bellmanFordNegativeCycle(graph, 4, 0)
15+
16+
expect(result.hasNegativeCycle).toBe(false)
17+
expect(result.dist[3]).toBe(6) // shortest distance from 0 to 3
18+
})
19+
20+
test('should detect negative cycle', () => {
21+
const graph = [
22+
[0, 1, 1],
23+
[1, 2, -1],
24+
[2, 0, -1]
25+
]
26+
const result = bellmanFordNegativeCycle(graph, 3, 0)
27+
28+
expect(result.hasNegativeCycle).toBe(true)
29+
})

0 commit comments

Comments
 (0)