UNPKG

1.31 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.dfs = void 0;
4const each = require("lodash.foreach");
5/*
6 * A helper that preforms a pre- or post-order traversal on the input graph
7 * and returns the nodes in the order they were visited. If the graph is
8 * undirected then this algorithm will navigate using neighbors. If the graph
9 * is directed then this algorithm will navigate using successors.
10 *
11 * Order must be one of "pre" or "post".
12 */
13function dfs(g, vs, order) {
14 if (!Array.isArray(vs)) {
15 vs = [vs];
16 }
17 const navigation = (g.isDirected() ? g.successors : g.neighbors).bind(g);
18 const acc = [];
19 const visited = {};
20 each(vs, (v) => {
21 if (!g.hasNode(v)) {
22 throw new Error('Graph does not have node: ' + v);
23 }
24 doDfs(g, v, order === 'post', visited, navigation, acc);
25 });
26 return acc;
27}
28exports.dfs = dfs;
29function doDfs(g, v, postorder, visited, navigation, acc) {
30 if (!(v in visited)) {
31 visited[v] = true;
32 if (!postorder) {
33 acc.push(v);
34 }
35 each(navigation(v), function (w) {
36 doDfs(g, w, postorder, visited, navigation, acc);
37 });
38 if (postorder) {
39 acc.push(v);
40 }
41 }
42}
43//# sourceMappingURL=dfs.js.map
\No newline at end of file