Skip to content

Commit 568b195

Browse files
authored
Update README.MD
1 parent 43356b5 commit 568b195

1 file changed

Lines changed: 31 additions & 0 deletions

File tree

  • L-A/0001 MemoizedNthNumberFibonacci ( L-A )/0002 BFSTraverseGraph

L-A/0001 MemoizedNthNumberFibonacci ( L-A )/0002 BFSTraverseGraph/README.MD

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,37 @@
33
Implement 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)

0 commit comments

Comments
 (0)