Breadth-First Search (BFS)
Learn BFS traversal with interactive graph visualization
intermediate Time: O(V + E) Space: O(V)
Breadth-First Search (BFS)
BFS is a graph traversal algorithm that explores all neighbors at the current depth before moving to nodes at the next depth level.
Key Concepts
- Uses a queue data structure (FIFO)
- Explores nodes level by level
- Finds the shortest path in unweighted graphs
Interactive Visualization
BFS Traversal
Starting BFS from node A
Speed
Step 1 of 21
Implementation
1function bfs(graph, start) {2 const visited = new Set();3 const queue = [start];4 visited.add(start);5 6 while (queue.length > 0) {7 const current = queue.shift();8 console.log(current); // Process node9 10 for (const neighbor of graph[current]) {11 if (!visited.has(neighbor)) {12 visited.add(neighbor);13 queue.push(neighbor);14 }15 }16 }17}Algorithm Steps
- Start at the source node, add it to the queue
- Mark the source as visited
- While queue is not empty:
- Dequeue a node
- Process it (print, store, etc.)
- Add all unvisited neighbors to the queue
- Mark neighbors as visited
Complexity
| Metric | Complexity |
|---|---|
| Time | O(V + E) |
| Space | O(V) |
Where V = vertices, E = edges
Use Cases
- Shortest path in unweighted graphs
- Level-order traversal of trees
- Finding connected components
- Social network friend suggestions (people within N connections)
- Web crawlers (exploring links level by level)
Related Topics
graphs traversal queue
Ad