Skip to content

Instantly share code, notes, and snippets.

@sranso
Last active July 3, 2016 23:28
Show Gist options
  • Save sranso/924fdf7160dd87995ce66094a6fff72c to your computer and use it in GitHub Desktop.
Save sranso/924fdf7160dd87995ce66094a6fff72c to your computer and use it in GitHub Desktop.
function Node(val, num) {
this.val = val;
this.num = num;
}
var a = new Node('a', 1);
var b = new Node('b', 1);
var c = new Node('c', 1);
var d = new Node('d', 1);
var e = new Node('e', 1);
var f = new Node('f', 1);
var g = new Node('g', 1);
var g2 = new Node('g', 2);
var h = new Node('h', 1);
var graph = {
a: [b, c, g],
b: [d, e, f],
c: [g2],
g: [h]
};
function traverseDFS(root, target, graph, visited) {
if (!visited) visited = {};
if (root.val.toString() === target) {
return root;
}
var graphRoot = graph[root.val];
if (!graphRoot) return;
for (var edge = 0; edge < graphRoot.length; edge++) {
var graphRootEdge = graphRoot[edge];
var result;
if (!visited[graphRootEdge.val + graphRootEdge.num]) {
visited[graphRootEdge.val + graphRootEdge.num] = 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