Skip to content

Instantly share code, notes, and snippets.

@woonketwong
Created January 12, 2014 19:09
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 woonketwong/8388997 to your computer and use it in GitHub Desktop.
Save woonketwong/8388997 to your computer and use it in GitHub Desktop.
Given a directed graph, design an algorithm to find out whether there is a route between two nodes using DFS.
var search = function(startNode, endNode){
//visit startNode
console.log("Visting:", startNode.key);
if (startNode.key === endNode.key){
return true;
}
startNode.visit = true;
for(var i = 0; i < startNode.next.length; i++){
if(startNode.next[i].visit === false){
if (search(startNode.next[i], endNode)){
return true;
}
}
}
return false;
}
// make a directed graph
// 1
// | | |
// 2 3 4
// | |
// 5 7
// |
// 6
// var makeNode = function(key, value){
// var obj = {"key": key,
// "value": value,
// "next": [],
// visit: false};
// return obj;
// }
// var root = makeNode("1", "apple");
// var node1 = makeNode("2", "orange");
// var node2 = makeNode("3", "kiwi");
// var node3 = makeNode("4", "banana");
// root.next.push(node1);
// root.next.push(node2);
// root.next.push(node3);
// var node1 = makeNode("5", "banana");
// var node2 = makeNode("6", "blueberry");
// root.next[0].next.push(node1);
// root.next[0].next[0].next.push(node2);
// var node1 = makeNode("7", "grape");
// root.next[2].next.push(node1);
// // should be balanced
// console.log(search(root, node1));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment