Skip to content

Commit edd0681

Browse files
committed
working process, test cases added
1 parent eb82bf2 commit edd0681

File tree

3 files changed

+42
-26
lines changed

3 files changed

+42
-26
lines changed

L-A/0001 MemoizedNthNumberFibonacci ( L-A )/0002 BFSTraverseGraph/BFS_traversegraph.js

Lines changed: 0 additions & 23 deletions
This file was deleted.
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
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+
}

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

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,23 @@
1+
# 0002 BFSTraverseGraph ( L-A )
2+
13
## Problem
24

35
Implement 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
6077
Pull 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

Comments
 (0)