Skip to content

Commit 9311783

Browse files
bellman-ford
1 parent 00bdef8 commit 9311783

File tree

1 file changed

+26
-8
lines changed

1 file changed

+26
-8
lines changed

src/algorithms/graph/bellmanFord.js

Lines changed: 26 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -7,31 +7,49 @@ export default function runBellmanFord(nodes, edges, source) {
77

88
// Relax edges |V|-1 times
99
for (let i = 0; i < nodes.length - 1; i++) {
10+
let updated = false;
1011
for (const edge of edges) {
11-
const { from, to, weight } = edge;
12+
const from = edge.u ?? edge.from;
13+
const to = edge.v ?? edge.to;
14+
const weight = edge.w ?? edge.weight;
15+
1216
const step = {
1317
type: "relax",
1418
iteration: i + 1,
15-
edge,
16-
prevDistance: dist[to]
19+
edge: { u: from, v: to, w: weight },
20+
prevDistance: dist[to],
1721
};
1822

19-
if (dist[from] + weight < dist[to]) {
23+
// ✅ Important: Check dist[from] !== Infinity before relaxing
24+
if (dist[from] !== Infinity && dist[from] + weight < dist[to]) {
2025
dist[to] = dist[from] + weight;
2126
step.updatedDistance = dist[to];
27+
updated = true;
28+
} else {
29+
step.type = "skip";
2230
}
2331

2432
steps.push(step);
2533
}
34+
35+
// Optimization: if no update in this pass, break early
36+
if (!updated) break;
2637
}
2738

2839
// Check for negative weight cycles
2940
for (const edge of edges) {
30-
const { from, to, weight } = edge;
31-
if (dist[from] + weight < dist[to]) {
32-
steps.push({ type: "negativeCycle", edge });
41+
const from = edge.u ?? edge.from;
42+
const to = edge.v ?? edge.to;
43+
const weight = edge.w ?? edge.weight;
44+
45+
if (dist[from] !== Infinity && dist[from] + weight < dist[to]) {
46+
steps.push({ type: "negative-cycle", edge: { u: from, v: to, w: weight } });
3347
}
3448
}
3549

36-
return steps;
50+
// Push final state step for visualization
51+
steps.push({ type: "done", distances: { ...dist } });
52+
53+
// Return both steps & final distances
54+
return { steps, distances: dist };
3755
}

0 commit comments

Comments
 (0)