Skip to content

Commit

Permalink
Merge pull request #69 from krm35/feature/shortestPaths
Browse files Browse the repository at this point in the history
Add a shortestPaths function
  • Loading branch information
curran authored Aug 3, 2023
2 parents 92a6887 + ef9666b commit 9540161
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
25 changes: 25 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ export function Graph(serialized?: Serialized) {
lowestCommonAncestors,
topologicalSort,
shortestPath,
shortestPaths,
serialize,
deserialize,
};
Expand Down Expand Up @@ -390,6 +391,30 @@ export function Graph(serialized?: Serialized) {
return path();
}

function shortestPaths(source: NodeId, destination: NodeId) {
let path = shortestPath(source, destination);
const paths = [path],
removedEdges = [],
weight = path.weight;
while (weight) {
removeEdge(path[0], path[1]);
removeEdge(path[1], path[0]);
removedEdges.push([path[0], path[1]]);
try {
path = shortestPath(source, destination);
if (!path.weight || weight < path.weight) break;
paths.push(path);
} catch (e) {
break;
}
}
for (const [u, v] of removedEdges) {
addEdge(u, v);
addEdge(v, u);
}
return paths;
}

// Serializes the graph.
function serialize() {
const serialized: Serialized = {
Expand Down
19 changes: 19 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -426,6 +426,25 @@ describe("Graph", function () {
withWeight(["a", "b", "c"], 2)
);
});

it("Should compute shortest paths on six edges.", function () {
var graph = Graph()
.addEdge("a", "b")
.addEdge("b", "c")
.addEdge("a", "d")
.addEdge("d", "c")
.addEdge("a", "e")
.addEdge("e", "f")
.addEdge("f", "c");
assert.deepEqual(graph.shortestPaths("a", "c"), [
withWeight(["a", "b", "c"], 2),
withWeight(["a", "d", "c"], 2),
]);
// need to check nodes are still present because we remove them to get all shortest paths
const nodes = ["a", "b", "c", "d", "e", "f"];
assert.equal(graph.nodes().length, nodes.length);
nodes.forEach((node) => assert(contains(graph.nodes(), node)));
});
});

describe("hadEdge", function () {
Expand Down

0 comments on commit 9540161

Please sign in to comment.