Created
February 18, 2014 14:42
-
-
Save jack-wong-build/9072292 to your computer and use it in GitHub Desktop.
Breadth first search.
This file contains 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
function breadthFirstSearch(node){ | |
// build a queue | |
var q = []; | |
// initialize q | |
q.push(node); | |
var currentNode = null; | |
while(q.length !== 0){ | |
currentNode = q.shift(); | |
// visit node | |
console.log(currentNode.value); | |
currentNode.visited = true; | |
for (var i = 0; i < currentNode.children.length; i++){ | |
if (currentNode.children[i].visited === false){ | |
q.push(currentNode.children[i]); | |
} | |
} | |
} | |
} | |
// a = {value:1, visited:false, children:[]}; | |
// b = {value:2, visited:false, children:[]}; | |
// c = {value:3, visited:false, children:[]}; | |
// d = {value:4, visited:false, children:[]}; | |
// e = {value:15, visited:false, children:[]}; | |
// f = {value:6, visited:false, children:[]}; | |
// g = {value:7, visited:false, children:[]}; | |
// h = {value:8, visited:false, children:[]}; | |
// a.children.push(b); | |
// a.children.push(c); | |
// a.children.push(d); | |
// b.children.push(e); | |
// c.children.push(f); | |
// d.children.push(g); | |
// e.children.push(h); | |
// breathFirstSearch(a); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment