Breadth-First Search (BFS)
Breadth-First Search (BFS) is one of very common traversal algorithm that shows up almost everywhere when dealing with graphs, grids, shortest paths.
What is BFS?
At its core, BFS algorithm explores a graph level by level.
Start from a node, visit all its neighbors, then all their neighbors, and so on. It expands outward evenly—like ripples in water.
To make that work, BFS uses a queue (FIFO):
- Add new nodes to the back
- Process from the front
BFS vs DFS (Quick Comparison)
There are two common ways to traverse graphs:
| BFS | DFS | |
|---|---|---|
| Strategy | Explore neighbors first | Go as deep as possible |
| Data structure | Queue | Stack / recursion |
| Strength | Shortest path (unweighted) | Memory-efficient paths |
A good mental model:
- BFS = wide
- DFS = deep
Why BFS Matters
The reason people use BFS is that it finds the shortest path in unweighted graphs because it explores in layers, the first time you reach a node, you have taken the minimum number of steps.
This is why BFS is perfect for problems in which you have to find the shortest path but their is no weights on the edges or they are same
Common Use Cases
You’ll see BFS in:
- Shortest paths (grids, maps)
- Web crawling
- Social graphs (degrees of separation)
- Cycle detection (see directed and undirected)
- Checking bipartite graphs
Remember:
- Use BFS when you care about shortest paths
- Use DFS when you just need to explore
JavaScript Implementation
function bfs(graph, start) {
const queue = [start]; // do not use array as a queue, use a proper queue implementation
const visited = new Set([start]);
while (queue.length) {
const node = queue.shift();
console.log(node);
for (const neighbor of graph[node] || []) {
if (!visited.has(neighbor)) {
visited.add(neighbor);
queue.push(neighbor);
}
}
}
}
There are also some more variants of BFS I will cover these later:
- BFS with revisiting nodes
- Multi-Source BFS
- 0-1 BFS