File tree Expand file tree Collapse file tree
L-A/0001 MemoizedNthNumberFibonacci ( L-A )/0002 BFSTraverseGraph Expand file tree Collapse file tree Original file line number Diff line number Diff line change 33Implement a JavaScript function that implements a breadth-first search (BFS) algorithm to traverse a graph.
44
55
6+ ## Solution
7+
8+ ``` javascript
9+ class Node {
10+ constructor (value , neighbors = []) {
11+ this .value = value;
12+ this .neighbors = neighbors;
13+ }
14+ }
15+
16+ function bfs (start , target ) {
17+ const queue = [start];
18+ const visited = new Set ();
19+
20+ while (queue .length ) {
21+ const node = queue .shift ();
22+ if (node .value === target) return true ;
23+ if (visited .has (node)) continue ;
24+ visited .add (node);
25+
26+ queue .push (... node .neighbors );
27+ }
28+
29+ return false ;
30+ }
31+ ```
32+
633## References
734
835- [ GeeksforGeeks] ( https://www.geeksforgeeks.org/breadth-first-search-or-bfs-for-a-graph/ )
36+ - [ StackOverflow] ( https://stackoverflow.com/questions/2505431/breadth-first-search-and-depth-first-search )
37+
38+ ## Problem Added By
39+ - [ GitHub] ( https://github.com/Akbar-Ahmed )
You can’t perform that action at this time.
0 commit comments