* 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)
| 13 | * @return {Array<T>} A BFS-traversed order of nodes. |
| 14 | */ |
| 15 | function 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 | |
| 39 | export default breadthFirstSearch; |
no test coverage detected