mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-05 00:01:37 +08:00
Add Graph BFS algorithm (#169)
* Add Graph BFS algorithm * updating DIRECTORY.md * Fix failing tests * updating DIRECTORY.md * Fix further failing tests Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com>
This commit is contained in:
@ -30,6 +30,31 @@ class Graph {
|
||||
console.log(i + ' -> ' + vertex)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints the Breadth first traversal of the graph from source.
|
||||
*
|
||||
* @param {number} source The source vertex to start BFS.
|
||||
*/
|
||||
bfs (source) {
|
||||
const queue = []
|
||||
const visited = new Set()
|
||||
queue.unshift([source, 0]) // level of source is 0
|
||||
visited.add(source)
|
||||
while (queue.length) {
|
||||
const front = queue[0]
|
||||
const node = front[0]
|
||||
const level = front[1]
|
||||
queue.shift() // remove the front of the queue
|
||||
console.log(`Visited node ${node} at level ${level}.`)
|
||||
for (const next of this.adjacencyMap[node]) {
|
||||
if (!visited.has(next)) { // not visited
|
||||
queue.unshift([next, level + 1]) // level 1 more than current
|
||||
visited.add(next)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const example = () => {
|
||||
@ -37,8 +62,17 @@ const example = () => {
|
||||
g.addVertex(1)
|
||||
g.addVertex(2)
|
||||
g.addVertex(3)
|
||||
g.addVertex(4)
|
||||
g.addVertex(5)
|
||||
g.addEdge(1, 2)
|
||||
g.addEdge(1, 3)
|
||||
g.addEdge(2, 4)
|
||||
g.addEdge(2, 5)
|
||||
console.log('Printing the adjacency list:\n')
|
||||
g.printGraph()
|
||||
|
||||
// perform a breadth first search
|
||||
console.log('\nBreadth first search at node 1:\n')
|
||||
g.bfs(1)
|
||||
}
|
||||
example()
|
||||
|
Reference in New Issue
Block a user