Last active
March 22, 2016 02:58
-
-
Save jmsevold/cb480cb6ca4e4583f92e 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
class Queue { | |
constructor() { | |
this.items = []; | |
} | |
enq(obj) { | |
this.items.push(obj); | |
} | |
deq() { | |
return this.items.shift(); | |
} | |
isEmpty() { | |
return this.items.length === 0; | |
} | |
} | |
/* | |
An undirected graph. Print out each node and it's distance from the source | |
A | |
/ \ | |
B C | |
/ \ | |
D E | |
*/ | |
var graph = { | |
"A": ["B","C"], | |
"B": [], | |
"C": ["D","E"], | |
"D": [], | |
"E":[] | |
}; | |
var nodeNotVisited = (list,item) => { | |
if (list.indexOf(item) === -1) { | |
return true; | |
} | |
return false; | |
}; | |
// write a bfs function that returns an array of the vertices as they were visited | |
var bfs = (graph,node) => { | |
let visitedNodes = []; | |
let q = new Queue(); | |
q.enq(node); | |
visitedNodes.push(node); | |
while(!q.isEmpty()){ | |
let currentNode = q.deq(); | |
console.log(currentNode); | |
let neighbors = graph[currentNode]; | |
if(neighbors.length > 0){ | |
neighbors.forEach((neighbor) => { | |
if (nodeNotVisited(visitedNodes,neighbor)) { | |
visitedNodes.push(neighbor); | |
q.enq(neighbor); | |
} | |
}); | |
} | |
} | |
return visitedNodes; | |
}; | |
bfs(graph,"A"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment