Created
March 20, 2016 19:41
-
-
Save jmsevold/761c3b25065775993332 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; | |
} | |
} | |
// var Queue = function() { | |
// this.items = []; | |
// }; | |
// Queue.prototype.enq = function(obj) { | |
// this.items.push(obj); | |
// }; | |
// Queue.prototype.deq = function() { | |
// return this.items.shift(); | |
// }; | |
// Queue.prototype.isEmpty = function() { | |
// return this.items.length === 0; | |
// }; | |
class Node{ | |
constructor(value,neighbors=[]){ | |
this.value = value; | |
this.neighbors = neighbors; | |
this.distance = null; | |
} | |
} | |
var node5 = new Node(5); | |
var node4 = new Node(4); | |
var node3 = new Node(3); | |
var node2 = new Node(2); | |
var node1 = new Node(1); | |
node5.neighbors = [node3]; | |
node4.neighbors = [node3]; | |
node3.neighbors = [node1,node4,node5]; | |
node2.neighbors = [node1]; | |
node1.neighbors = [node2,node3]; | |
/* | |
An undirected graph. Print out each node and it's distance from the source | |
1 | |
/ \ | |
2 3 | |
/ \ | |
4 5 | |
*/ | |
var bfs = (node) => { | |
var q = new Queue(); | |
q.enq(node); | |
node.distance = 0; | |
console.log("Node " + node.value + " is " + node.distance + " from " + "Node " + node.value + "(source)" ); | |
while(!q.isEmpty()){ | |
var currentNode = q.deq(); | |
currentNode.neighbors.forEach((neighbor) => { | |
if (neighbor.distance === null) { | |
neighbor.distance = currentNode.distance + 1; | |
console.log("Node " + neighbor.value + " is " + neighbor.distance + " from " + "Node " + node.value + "(source)" ); | |
q.enq(neighbor); | |
} | |
}); | |
} | |
}; | |
bfs(node1); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment