Skip to content

Commit

Permalink
Implement shortestPaths function
Browse files Browse the repository at this point in the history
  • Loading branch information
mstou committed Sep 2, 2018
1 parent 4d0f34f commit 4eba58f
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
1 change: 1 addition & 0 deletions lib/alg/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ module.exports = {
postorder: require("./postorder"),
preorder: require("./preorder"),
prim: require("./prim"),
shortestPaths: require("./shortest-paths"),
tarjan: require("./tarjan"),
topsort: require("./topsort")
};
40 changes: 40 additions & 0 deletions lib/alg/shortest-paths.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
var dijkstra = require("./dijkstra"),
bellmanFord = require("./bellman-ford");

module.exports = shortestPaths;

function shortestPaths(g, source, weightFn, edgeFn){
return runShortestPaths(g,
source,
weightFn,
edgeFn || function(v) { return g.outEdges(v); });
}

function runShortestPaths(g, source, weightFn, edgeFn) {
if (weightFn === undefined) {
return dijkstra(g, source, weightFn, edgeFn);
}

var negativeEdgeExists = false;
var nodes = g.nodes();

for (var i = 0; i < nodes.length; i++) {
var adjList = edgeFn(nodes[i]);

for (var j = 0; j < adjList.length; j++) {
var edge = adjList[j];
var inVertex = edge.v === nodes[i] ? edge.v : edge.w;
var outVertex = inVertex === edge.v ? edge.w : edge.v;

if (weightFn({ v: inVertex, w: outVertex }) < 0) {
negativeEdgeExists = true;
}
}

if (negativeEdgeExists) {
return bellmanFord(g, source, weightFn, edgeFn);
}
}

return dijkstra(g, source, weightFn, edgeFn);
}

0 comments on commit 4eba58f

Please sign in to comment.