Last active
July 2, 2016 22:42
-
-
Save sranso/053ff199b8f0fe9ecd10c8895bf21a34 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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