MCPcopy
hub / github.com/yangshun/lago / breadthFirstSearch

Function breadthFirstSearch

src/algorithms/breadthFirstSearch.ts:15–37  ·  view source on GitHub ↗

* Performs a breadth-first search on a graph given a starting node. * @param {Object} graph Node to array of neighboring nodes. * @param {number|string} source Source node to start traversal from. * It has to exist as a node in the graph. * @return {Array } A BFS-traversed order of nodes.

(graph: Graph<T>, source: T)

Source from the content-addressed store, hash-verified

13 * @return {Array<T>} A BFS-traversed order of nodes.
14 */
15function breadthFirstSearch<T>(graph: Graph<T>, source: T): Array<T> {
16 if (Object.keys(graph).length === 0) {
17 return [];
18 }
19
20 const queue = new Queue<T>();
21 queue.enqueue(source);
22
23 const visited = new Set<T>([source]);
24
25 while (!queue.isEmpty()) {
26 const node = nullthrows(queue.dequeue());
27 visited.add(node);
28 graph[String(node)].forEach((neighbor: T) => {
29 if (visited.has(neighbor)) {
30 return;
31 }
32 queue.enqueue(neighbor);
33 });
34 }
35
36 return Array.from(visited);
37}
38
39export default breadthFirstSearch;

Callers 1

Calls 5

enqueueMethod · 0.95
isEmptyMethod · 0.95
dequeueMethod · 0.95
nullthrowsFunction · 0.85
addMethod · 0.80

Tested by

no test coverage detected