Skip to content

Commit 4501ac2

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

File tree

1 file changed

+3
-4
lines changed

1 file changed

+3
-4
lines changed

Graphs/BellmanFordNegativeCycle.js

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,18 +10,17 @@ function bellmanFordNegativeCycle(graph, vertices, start) {
1010
const dist = new Array(vertices).fill(Infinity)
1111
dist[start] = 0
1212

13-
// relax all edges (V - 1) times
1413
for (let i = 0; i < vertices - 1; i++) {
15-
for (let [u, v, w] of graph) {
14+
for (const [u, v, w] of graph) {
1615
if (dist[u] !== Infinity && dist[u] + w < dist[v]) {
1716
dist[v] = dist[u] + w
1817
}
1918
}
2019
}
2120

22-
// check for negative cycle
23-
for (let [u, v, w] of graph) {
21+
for (const [u, v, w] of graph) {
2422
if (dist[u] !== Infinity && dist[u] + w < dist[v]) {
23+
// A shorter path found after V-1 iterations means a negative cycle exists
2524
return { hasNegativeCycle: true, dist }
2625
}
2726
}

0 commit comments

Comments
 (0)