Skip to content
Go back

Breadth-First Search (BFS) and Its Variants

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):


BFS vs DFS (Quick Comparison)

There are two common ways to traverse graphs:

BFSDFS
StrategyExplore neighbors firstGo as deep as possible
Data structureQueueStack / recursion
StrengthShortest path (unweighted)Memory-efficient paths

A good mental model:


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:

Remember:


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:


Share this post on:

Previous Post
Web Clipboard Notes (Summary)
Next Post
Renaming Local and Remote Git Branches