Created
November 8, 2021 23:07
-
-
Save cagataycali/efb8ddf6f9bd82251f63b5755ca5d01b to your computer and use it in GitHub Desktop.
[JavaScript] Graph breath first search
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 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