Skip to content

Commit

Permalink
Use neighbors to perform DFS on undirected graphs
Browse files Browse the repository at this point in the history
  • Loading branch information
cpettitt committed Nov 23, 2015
1 parent ffcc1a1 commit 5a84ef8
Showing 1 changed file with 9 additions and 6 deletions.
15 changes: 9 additions & 6 deletions lib/alg/dfs.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@ module.exports = dfs;

/*
* A helper that preforms a pre- or post-order traversal on the input graph
* and returns the nodes in the order they were visited. This algorithm treats
* the input as undirected.
* and returns the nodes in the order they were visited. If the graph is
* undirected then this algorithm will navigate using neighbors. If the graph
* is directed then this algorithm will navigate using successors.
*
* Order must be one of "pre" or "post".
*/
Expand All @@ -14,25 +15,27 @@ function dfs(g, vs, order) {
vs = [vs];
}

var navigation = (g.isDirected() ? g.successors : g.neighbors).bind(g);

var acc = [],
visited = {};
_.each(vs, function(v) {
if (!g.hasNode(v)) {
throw new Error("Graph does not have node: " + v);
}

doDfs(g, v, order === "post", visited, acc);
doDfs(g, v, order === "post", visited, navigation, acc);
});
return acc;
}

function doDfs(g, v, postorder, visited, acc) {
function doDfs(g, v, postorder, visited, navigation, acc) {
if (!_.has(visited, v)) {
visited[v] = true;

if (!postorder) { acc.push(v); }
_.each(g.successors(v), function(w) {
doDfs(g, w, postorder, visited, acc);
_.each(navigation(v), function(w) {
doDfs(g, w, postorder, visited, navigation, acc);
});
if (postorder) { acc.push(v); }
}
Expand Down

0 comments on commit 5a84ef8

Please sign in to comment.