Write a function `bfs(graph, start)` that performs BFS on an adjacency list graph and returns the visit order.
Problem Statement
Write a function `bfs(graph, start)` that performs BFS on an adjacency list graph and returns the visit order.
Complexity
Time Complexity: -
Space Complexity: -
Hints
š” Hint 1:
BFS uses a queue (FIFO) and visits nodes level by level.
š” Hint 2:
Track visited nodes with a Set to avoid cycles.
š” Hint 3:
Dequeue a node, add to result, enqueue its unvisited neighbors.
ā
Solution:
```javascript
function bfs(graph, start) {
const visited = new Set();
const queue = [start];
const result = [];
visited.add(start);
while (queue.length > 0) {
const node = queue.shift();
result.push(node);
for (const neighbor of (graph[node] || [])) {
if (!visited.has(neighbor)) {
visited.add(neighbor);
queue.push(neighbor);
}
}
}
return result;
}
```