1+ # 0002 BFSTraverseGraph ( L-A )
2+
13## Problem
24
35Implement a JavaScript function that implements a breadth-first search (BFS) algorithm to traverse a graph.
46
57
8+ ## Test Cases
9+ const a = new Node('a');
10+ const b = new Node('b');
11+ const c = new Node('c');
12+ const d = new Node('d');
13+ const e = new Node('e');
14+ const f = new Node('f');
15+
16+ - a.neighbors = [ b, c, e] ; console.log(bfs(a, 'f')); // false
17+ - b.neighbors = [ d, e] ; console.log(bfs(b, 'd')); // true
18+ - c.neighbors = [ f] ; console.log(bfs(c, 'f')); // true
19+
20+
621## Solution
722
823``` javascript
@@ -29,9 +44,11 @@ class Node {
2944 return false ;
3045 }
3146 ```
32-
33- ## How it works
3447
48+ ## How it works
49+
50+ - We create a class called Node that takes a value and an array of neighbors as parameters.
51+ - We create a function called bfs that takes a start node and a target node as parameters.
3552- We create a queue and add the start node to it.
3653- We create a visited set to keep track of the nodes we have visited.
3754- We loop through the queue while it is not empty.
@@ -59,4 +76,4 @@ class Node {
5976## Contributing
6077Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.
6178
62- Please make sure to update tests as appropriate.
79+ Please make sure to update tests as appropriate.
0 commit comments