* Prints the Breadth first traversal of the graph from source. * @param {number} source The source vertex to start BFS.
(source, output = (value) => console.log(value))
| 35 | * @param {number} source The source vertex to start BFS. |
| 36 | */ |
| 37 | bfs(source, output = (value) => console.log(value)) { |
| 38 | const queue = [[source, 0]] // level of source is 0 |
| 39 | const visited = new Set() |
| 40 | |
| 41 | while (queue.length) { |
| 42 | const [node, level] = queue.shift() // remove the front of the queue |
| 43 | if (visited.has(node)) { |
| 44 | // visited |
| 45 | continue |
| 46 | } |
| 47 | |
| 48 | visited.add(node) |
| 49 | output(`Visited node ${node} at level ${level}.`) |
| 50 | for (const next of this.adjacencyMap[node]) { |
| 51 | queue.push([next, level + 1]) // level 1 more than current |
| 52 | } |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | /** |
| 57 | * Prints the Depth first traversal of the graph from source. |