Breadth-First Search (BFS)
In graphs, Breadth-First Search (BFS) is commonly used to explore vertices level by level, meaning that all vertices at the present depth are processed before moving on to the vertices at the next depth level.
We can perform BFS using a queue, which ensures that we process vertices in the order they are discovered.
Try implementing the solution on your own first. If you need help, refer to the walkthrough or the solution code.
// Implement a function `bfs` that accepts two arguments: the adjacency list
// representing an acyclic graph and a starting vertex (source).
// The function should print the vertices in breadth-first
// traversal order.
function bfs(adjList, source) {
// implementation goes here
}
const adjList = new Map();
adjList.set(1, []);
adjList.set(2, [1, 3, 4]);
adjList.set(3, [5]);
adjList.set(4, [6]);
adjList.set(5, []);
adjList.set(6, []);
adjList.set(7, [6]);
bfs(adjList, 2); // 2, 1, 3, 4, 5, 6 or 2, 4, 3, 1, 6, 5
// Again, the order depends on which neighbor node we explore first







