Skip to content
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
34 changes: 26 additions & 8 deletions src/algorithms/graph/bellmanFord.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,31 +7,49 @@ export default function runBellmanFord(nodes, edges, source) {

// Relax edges |V|-1 times
for (let i = 0; i < nodes.length - 1; i++) {
let updated = false;
for (const edge of edges) {
const { from, to, weight } = edge;
const from = edge.u ?? edge.from;
const to = edge.v ?? edge.to;
const weight = edge.w ?? edge.weight;

const step = {
type: "relax",
iteration: i + 1,
edge,
prevDistance: dist[to]
edge: { u: from, v: to, w: weight },
prevDistance: dist[to],
};

if (dist[from] + weight < dist[to]) {
// ✅ Important: Check dist[from] !== Infinity before relaxing
if (dist[from] !== Infinity && dist[from] + weight < dist[to]) {
dist[to] = dist[from] + weight;
step.updatedDistance = dist[to];
updated = true;
} else {
step.type = "skip";
}

steps.push(step);
}

// Optimization: if no update in this pass, break early
if (!updated) break;
}

// Check for negative weight cycles
for (const edge of edges) {
const { from, to, weight } = edge;
if (dist[from] + weight < dist[to]) {
steps.push({ type: "negativeCycle", edge });
const from = edge.u ?? edge.from;
const to = edge.v ?? edge.to;
const weight = edge.w ?? edge.weight;

if (dist[from] !== Infinity && dist[from] + weight < dist[to]) {
steps.push({ type: "negative-cycle", edge: { u: from, v: to, w: weight } });
}
}

return steps;
// Push final state step for visualization
steps.push({ type: "done", distances: { ...dist } });

// Return both steps & final distances
return { steps, distances: dist };
}
Loading