Skip to content

Instantly share code, notes, and snippets.

@jmsevold
Created March 20, 2016 19:39
Show Gist options
  • Save jmsevold/c9faeb602453ced83bb9 to your computer and use it in GitHub Desktop.
Save jmsevold/c9faeb602453ced83bb9 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;
}
}
class Node{
constructor(value,children=[]){
this.value = value;
this.children = children;
this.distance = null;
}
}
var node5 = new Node(5);
var node4 = new Node(4);
var node3 = new Node(3, [node4, node5]);
var node2 = new Node(2);
var node1 = new Node(1, [node2, node3]);
var bfs = (node) => {
var q = new Queue();
q.enq(node);
node.distance = 0;
while(!q.isEmpty()){
var currentNode = q.deq();
console.log("Node " + currentNode.value + " distance: " + currentNode.distance + " from source.");
if(currentNode.children.length > 0){
currentNode.children.forEach((child) => {
child.distance = currentNode.distance + 1;
q.enq(child);
});
}
}
};
bfs(node1);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment