Skip to content

Instantly share code, notes, and snippets.

@jmsevold
Last active March 22, 2016 02:58
Show Gist options
  • Save jmsevold/cb480cb6ca4e4583f92e to your computer and use it in GitHub Desktop.
Save jmsevold/cb480cb6ca4e4583f92e to your computer and use it in GitHub Desktop.
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