Skip to content

Instantly share code, notes, and snippets.

@sranso
Last active July 2, 2016 22:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sranso/053ff199b8f0fe9ecd10c8895bf21a34 to your computer and use it in GitHub Desktop.
Save sranso/053ff199b8f0fe9ecd10c8895bf21a34 to your computer and use it in GitHub Desktop.
var graph = {
a: ['b', 'c'],
b: ['d', 'e', 'f'],
c: ['g'],
g: ['h']
};
function traverseDFS(root, target, graph, visited) {
if (!visited) visited = {};
if (root.toString() === target.toString()) return target;
var graphRoot = graph[root];
if (!graphRoot) return;
// traverse edges of the root
for (var edge = 0; edge < graphRoot.length; edge++) {
var graphRootEdge = graphRoot[edge];
var result;
if (!visited[graphRootEdge]) {
visited[graphRootEdge] = true;
result = traverseDFS(graphRootEdge, target, graph, visited);
}
if (result) return result;
}
return;
}
traverseDFS('a', 'g', graph);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment