Skip to content

Commit cb0aff9

Browse files
sahilbansal17github-actions
and
github-actions
authored
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>
1 parent 25dac3a commit cb0aff9

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

Data-Structures/Graph/Graph.js

+34
Original file line numberDiff line numberDiff line change
@@ -30,15 +30,49 @@ class Graph {
3030
console.log(i + ' -> ' + vertex)
3131
}
3232
}
33+
34+
/**
35+
* Prints the Breadth first traversal of the graph from source.
36+
*
37+
* @param {number} source The source vertex to start BFS.
38+
*/
39+
bfs (source) {
40+
const queue = []
41+
const visited = new Set()
42+
queue.unshift([source, 0]) // level of source is 0
43+
visited.add(source)
44+
while (queue.length) {
45+
const front = queue[0]
46+
const node = front[0]
47+
const level = front[1]
48+
queue.shift() // remove the front of the queue
49+
console.log(`Visited node ${node} at level ${level}.`)
50+
for (const next of this.adjacencyMap[node]) {
51+
if (!visited.has(next)) { // not visited
52+
queue.unshift([next, level + 1]) // level 1 more than current
53+
visited.add(next)
54+
}
55+
}
56+
}
57+
}
3358
}
3459

3560
const example = () => {
3661
const g = new Graph()
3762
g.addVertex(1)
3863
g.addVertex(2)
3964
g.addVertex(3)
65+
g.addVertex(4)
66+
g.addVertex(5)
4067
g.addEdge(1, 2)
4168
g.addEdge(1, 3)
69+
g.addEdge(2, 4)
70+
g.addEdge(2, 5)
71+
console.log('Printing the adjacency list:\n')
4272
g.printGraph()
73+
74+
// perform a breadth first search
75+
console.log('\nBreadth first search at node 1:\n')
76+
g.bfs(1)
4377
}
4478
example()

0 commit comments

Comments
 (0)