Skip to content

Commit

Permalink
Merge pull request #84 from eush77/bellman-ford-early-stop
Browse files Browse the repository at this point in the history
Stop early in Bellman-Ford
  • Loading branch information
felipernb committed Aug 3, 2014
2 parents a2d30b0 + a3264ae commit bf5489c
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 bf5489c

Please sign in to comment.