Skip to content

Commit 9540161

Browse files
authored
Merge pull request #69 from krm35/feature/shortestPaths
Add a shortestPaths function
2 parents 92a6887 + ef9666b commit 9540161

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

src/index.ts

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ export function Graph(serialized?: Serialized) {
3333
lowestCommonAncestors,
3434
topologicalSort,
3535
shortestPath,
36+
shortestPaths,
3637
serialize,
3738
deserialize,
3839
};
@@ -390,6 +391,30 @@ export function Graph(serialized?: Serialized) {
390391
return path();
391392
}
392393

394+
function shortestPaths(source: NodeId, destination: NodeId) {
395+
let path = shortestPath(source, destination);
396+
const paths = [path],
397+
removedEdges = [],
398+
weight = path.weight;
399+
while (weight) {
400+
removeEdge(path[0], path[1]);
401+
removeEdge(path[1], path[0]);
402+
removedEdges.push([path[0], path[1]]);
403+
try {
404+
path = shortestPath(source, destination);
405+
if (!path.weight || weight < path.weight) break;
406+
paths.push(path);
407+
} catch (e) {
408+
break;
409+
}
410+
}
411+
for (const [u, v] of removedEdges) {
412+
addEdge(u, v);
413+
addEdge(v, u);
414+
}
415+
return paths;
416+
}
417+
393418
// Serializes the graph.
394419
function serialize() {
395420
const serialized: Serialized = {

test.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -426,6 +426,25 @@ describe("Graph", function () {
426426
withWeight(["a", "b", "c"], 2)
427427
);
428428
});
429+
430+
it("Should compute shortest paths on six edges.", function () {
431+
var graph = Graph()
432+
.addEdge("a", "b")
433+
.addEdge("b", "c")
434+
.addEdge("a", "d")
435+
.addEdge("d", "c")
436+
.addEdge("a", "e")
437+
.addEdge("e", "f")
438+
.addEdge("f", "c");
439+
assert.deepEqual(graph.shortestPaths("a", "c"), [
440+
withWeight(["a", "b", "c"], 2),
441+
withWeight(["a", "d", "c"], 2),
442+
]);
443+
// need to check nodes are still present because we remove them to get all shortest paths
444+
const nodes = ["a", "b", "c", "d", "e", "f"];
445+
assert.equal(graph.nodes().length, nodes.length);
446+
nodes.forEach((node) => assert(contains(graph.nodes(), node)));
447+
});
429448
});
430449

431450
describe("hadEdge", function () {

0 commit comments

Comments
 (0)