Skip to content

Commit 03f7542

Browse files
committed
Support case of disconnected subgraphs
1 parent a229a88 commit 03f7542

2 files changed

Lines changed: 15 additions & 2 deletions

File tree

index.js

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -245,7 +245,9 @@ module.exports = function Graph(serialized){
245245
}
246246
});
247247
if (minNode === undefined) {
248-
throw new Error("No path exists.");
248+
// If we reach here, there's a disconnected subgraph, and we're done.
249+
q = {};
250+
return null;
249251
}
250252
delete q[minNode];
251253
return minNode;
@@ -279,7 +281,10 @@ module.exports = function Graph(serialized){
279281
nodeList.push(node);
280282
node = p[node];
281283
}
282-
nodeList.push(source);
284+
if (node !== source) {
285+
throw new Error("No path found");
286+
}
287+
nodeList.push(node);
283288
nodeList.reverse();
284289
return nodeList;
285290
}

test.js

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -378,6 +378,14 @@ describe("Graph", function() {
378378
.addEdge("d", "e");
379379
assert.throws(() => graph.shortestPath("a", "e"), /No path/);
380380
});
381+
382+
it("Should be robust to disconnected subgraphs.", function (){
383+
var graph = Graph()
384+
.addEdge("a", "b")
385+
.addEdge("b", "c")
386+
.addEdge("d", "e");
387+
assert.deepEqual(graph.shortestPath("a", "c"), ["a", "b", "c"]);
388+
});
381389
});
382390
});
383391

0 commit comments

Comments
 (0)