Skip to content

Commit

Permalink
Stop early in Bellman-Ford
Browse files Browse the repository at this point in the history
This also eliminates the need for a separate extra iteration.
  • Loading branch information
eush77 committed Aug 2, 2014
1 parent 43e3dbc commit a3264ae
Showing 1 changed file with 16 additions and 12 deletions.
28 changes: 16 additions & 12 deletions algorithms/graph/bellman_ford.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,31 +39,35 @@ var bellmanFord = function (graph, startNode) {
var sourceDistance;
var targetDistance;

for (var i = 0; i < adjacencyListSize - 1; i++) {
var iteration;
for (iteration = 0; iteration < adjacencyListSize; ++iteration) {
var somethingChanged = false;

for (var j = 0; j < edgesSize; j++) {
sourceDistance = minDistance[edges[j].source] + edges[j].weight;
targetDistance = minDistance[edges[j].target];

if (sourceDistance < targetDistance) {
somethingChanged = true;
minDistance[edges[j].target] = sourceDistance;
previousVertex[edges[j].target] = edges[j].source;
}
}
}

for (i = 0; i < edgesSize; i++) {
sourceDistance = minDistance[edges[i].source] + edges[i].weight;
targetDistance = minDistance[edges[i].target];

if (sourceDistance < targetDistance) {

// Empty 'distance' object indicates Negative-Weighted Cycle
return {
distance: {}
};
if (!somethingChanged) {
// Early stop.
break;
}
}

// If the loop did not break early, then there is a negative-weighted cycle.
if (iteration == adjacencyListSize) {
// Empty 'distance' object indicates Negative-Weighted Cycle
return {
distance: {}
};
}

return {
distance: minDistance,
previous: previousVertex
Expand Down

0 comments on commit a3264ae

Please sign in to comment.