Created
November 4, 2017 18:22
-
-
Save levymoreira/22aa06254d86ad98a8afbb8e877b3f8b to your computer and use it in GitHub Desktop.
JS bfs impl
This file contains 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 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