-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbfs.js
34 lines (27 loc) · 767 Bytes
/
bfs.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// return a BFS traversal of a graph
import Queue from '../../../dataStructure/queue/queue';
const bfs = (graph, start) => {
const visited = [];
const result = [];
const queue = new Queue(); // can also use JavaScript array
queue.add(start);
const startIndex = graph.vertices.indexOf(start);
visited[startIndex] = 1;
while (!queue.isEmpty()) {
const cur = queue.remove();
result.push(cur);
const index = graph.vertices.indexOf(cur);
visited[index] = 1;
const neighbors = graph.adjList.get(cur);
neighbors.forEach((n) => {
const nIndex = graph.vertices.indexOf(n);
if (visited[nIndex]) {
return;
}
visited[nIndex] = 1;
queue.add(n);
});
}
return result;
};
export default bfs;