Skip to content

Commit eb82bf2

Browse files
authored
Merge pull request #15 from Akbar-Ahmed/main
Added a problem along with solution
2 parents 6ff0876 + 8b72163 commit eb82bf2

File tree

2 files changed

+85
-0
lines changed

2 files changed

+85
-0
lines changed
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
class Node {
2+
constructor(value, neighbors = []) {
3+
this.value = value;
4+
this.neighbors = neighbors;
5+
}
6+
}
7+
8+
function bfs(start, target) {
9+
const queue = [start];
10+
const visited = new Set();
11+
12+
while (queue.length) {
13+
const node = queue.shift();
14+
if (node.value === target) return true;
15+
if (visited.has(node)) continue;
16+
visited.add(node);
17+
18+
queue.push(...node.neighbors);
19+
}
20+
21+
return false;
22+
}
23+
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
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

Comments
 (0)