MCPcopy
hub / github.com/TheAlgorithms/JavaScript / bfs

Method bfs

Data-Structures/Graph/Graph.js:37–54  ·  view source on GitHub ↗

* 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))

Source from the content-addressed store, hash-verified

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.

Callers 1

exampleFunction · 0.95

Calls 5

outputFunction · 0.85
logMethod · 0.45
hasMethod · 0.45
addMethod · 0.45
pushMethod · 0.45

Tested by

no test coverage detected