Skip to content

Instantly share code, notes, and snippets.

@levymoreira
Created November 4, 2017 18:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save levymoreira/22aa06254d86ad98a8afbb8e877b3f8b to your computer and use it in GitHub Desktop.
Save levymoreira/22aa06254d86ad98a8afbb8e877b3f8b to your computer and use it in GitHub Desktop.
JS bfs impl
class Node {
constructor(id, value, adjacent) {
this.id = id;
this.value = value;
this.adjacent = adjacent;
}
}
class Graph {
constructor(adjacent) {
this.adjacent = adjacent;
}
bfs(root, dest) {
const visited = [];
const searchList = [root];
while (searchList.length !== 0) {
const node = searchList.shift();
if (node.id === dest.id) {
return true;
}
if (visited.includes(node.id)) {
return false;
}
visited.push(node.id);
if (node.adjacent) {
searchList.push(...node.adjacent);
}
}
return false;
}
}
const test = (currentResult, expectedResult) => {
if (!_.isEqual(currentResult, expectedResult)) {
console.log('Error!');
console.log('Current Result:');
console.log(currentResult);
console.log('Expected Result:');
console.log(expectedResult);
} else {
console.log('Success.');
}
}
/*
a-> b
-> c -> d
*/
let id = 1;
const d = new Node(id++, 'd');
const b = new Node(id++, 'b');
const c = new Node(id++, 'c', [d]);
const a = new Node(id++, 'a', [b, c]);
var graph = new Graph([a]);
test(graph.bfs(a, d), true);
test(graph.bfs(b, a), false);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment