Skip to content

Instantly share code, notes, and snippets.

@cagataycali
Created November 8, 2021 23:07
Show Gist options
  • Select an option

  • Save cagataycali/efb8ddf6f9bd82251f63b5755ca5d01b to your computer and use it in GitHub Desktop.

Select an option

Save cagataycali/efb8ddf6f9bd82251f63b5755ca5d01b to your computer and use it in GitHub Desktop.
[JavaScript] Graph breath first search
class Node {
constructor(name) {
this.name = name;
this.children = [];
}
addChild(name) {
this.children.push(new Node(name));
return this;
}
breadthFirstSearch(array) {
const queue = [this];
while (queue.length) {
const item = queue.shift();
array.push(item.name);
item.children.forEach(child => queue.push(child))
}
return array;
}
}
/*
graph = A
/ | \
B C D
/ \ / \
E F G H
/ \ \
I J K
graph = {
name: "A",
children: [
{
name: "B",
children: [
{ name: "E", children: [] },
{
name: "F",
children: [
{ name: "I", children: [] },
{ name: "J", children: [] },
],
},
],
},
{ name: "C", children: [] },
{
name: "D",
children: [
{ name: "G", children: [{ name: "K", children: [] }] },
{ name: "H", children: [] },
],
},
],
};
*/
const graph = new Node("A");
graph.addChild("B").addChild("C").addChild("D");
graph.children[0].addChild("E").addChild("F");
graph.children[0].children[1].addChild("I").addChild("J");
graph.children[2].addChild("G").addChild("H");
graph.children[2].children[0].addChild("K");
const result = []
graph.breadthFirstSearch(result)
console.log(result);
// console.log(JSON.stringify(graph, null, 2));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment