depth-first
Version:
Depth first search directed graphs
27 lines (26 loc) • 879 B
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
function depthFirst(edges, node, opts = {}) {
const { reverse = false } = opts;
edges = reverse ? edges.map(([from, to]) => [to, from]) : edges;
const outEdges = new Map();
edges.forEach(([from, to]) => {
var _a, _b;
_b = (_a = outEdges.get(from)) === null || _a === void 0 ? void 0 : _a.push(to), (_b !== null && _b !== void 0 ? _b : outEdges.set(from, [to]));
});
const result = [];
const visited = new Map();
const dfs = (v) => {
var _a;
result.push(v);
visited.set(v, true);
for (const to of (_a = outEdges.get(v), (_a !== null && _a !== void 0 ? _a : []))) {
if (!visited.has(to)) {
dfs(to);
}
}
};
dfs(node);
return result;
}
exports.default = depthFirst;