|
| 1 | +## Problem |
| 2 | + |
| 3 | +Implement a JavaScript function that implements a breadth-first search (BFS) algorithm to traverse a graph. |
| 4 | + |
| 5 | + |
| 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 | + |
| 33 | + ## How it works |
| 34 | + |
| 35 | +- We create a queue and add the start node to it. |
| 36 | +- We create a visited set to keep track of the nodes we have visited. |
| 37 | +- We loop through the queue while it is not empty. |
| 38 | +- We shift the first node off the queue and check if it is the target node. |
| 39 | +- If it is, we return true. |
| 40 | +- If it is not, we check if we have visited the node already. |
| 41 | +- If we have, we continue. |
| 42 | +- If we have not, we add the node to the visited set. |
| 43 | +- We then push all of the neighbors of the node to the queue. |
| 44 | +- We then loop again. |
| 45 | +- We repeat this process until the queue is empty. |
| 46 | +- If we have not found the target node, we return false. |
| 47 | + |
| 48 | + |
| 49 | +## References |
| 50 | + |
| 51 | +- [GeeksforGeeks](https://www.geeksforgeeks.org/breadth-first-search-or-bfs-for-a-graph/) |
| 52 | +- [StackOverflow](https://stackoverflow.com/questions/2505431/breadth-first-search-and-depth-first-search) |
| 53 | + |
| 54 | + |
| 55 | +## Problem Added By |
| 56 | +- [GitHub](https://github.com/Akbar-Ahmed) |
| 57 | + |
| 58 | + |
| 59 | +## Contributing |
| 60 | +Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change. |
| 61 | + |
| 62 | +Please make sure to update tests as appropriate. |
0 commit comments