Breadth-first search

Explore a graph level by level from a start vertex using a queue, finding the shortest path in number of edges to everything reachable.

Description

Breadth-first search explores a graph in rings: first the start vertex, then all its neighbors, then all their unvisited neighbors, and so on. It uses a queue: take the vertex at the front, look at its neighbors, and add each one you haven't seen before to the back.

Because vertices are discovered in order of distance, BFS finds the shortest path in number of edges from the start to every reachable vertex. Record each vertex's parent as you discover it, and you can walk back from any vertex to reconstruct the path.

A visited set is essential: without it, cycles make BFS loop forever, and vertices with several paths are processed many times.

BFS powers "degrees of separation" in social networks, shortest routes when every step costs the same, web crawlers, finding everything within k hops, and solving puzzles where each move is one step. When edges have different weights, use Dijkstra's algorithm instead.

How it works

ABCDEF

The graph we'll search, starting from A

  1. A — B
  2. A — C
  3. B — D
  4. C — D
  5. C — E
  6. D — F
  7. E — F
The graph we'll search, starting from A

Step through: BFS from A, with the distance from A next to each vertex

A0BCDEF

Queue AVisited in order none yet

Step 1 of 22Start at A: mark it visited and put it in the queue.

0 comparisons

Complexity

OperationAverageWorst
Traverse from one start vertexEvery vertex is queued once and every edge checked once (twice if undirected).O(V + E)O(V + E)
Shortest path (unweighted)O(V + E)O(V + E)
With an adjacency matrixO(V²)O(V²)

Space: O(V) for the queue and the visited set

BFS can hold a whole level of the graph in its queue at once, which for wide graphs uses much more memory than depth-first search.

TypeScript implementation

BFS over an adjacency list that returns the visit order, each vertex's distance from the start, and the shortest path to a target.

breadth-first-search.ts
// Breadth-first search over an adjacency list. Vertices are marked visited
// when they're enqueued, so each one enters the queue exactly once.

type AdjacencyList = Record<string, string[]>;

export function bfs(graph: AdjacencyList, start: string) {
  const dist: Record<string, number> = { [start]: 0 };
  const parent: Record<string, string | null> = { [start]: null };
  const order: string[] = [];
  const queue = [start];
  let head = 0; // a moving index instead of queue.shift(), which is O(n)

  while (head < queue.length) {
    const v = queue[head++];
    order.push(v);
    for (const n of graph[v] ?? []) {
      if (n in dist) continue; // already visited
      dist[n] = dist[v] + 1;
      parent[n] = v;
      queue.push(n);
    }
  }
  return { order, dist, parent };
}

/** Shortest path in number of edges, or null if target is unreachable. */
export function shortestPath(graph: AdjacencyList, start: string, target: string): string[] | null {
  const { parent } = bfs(graph, start);
  if (!(target in parent)) return null;
  const path: string[] = [];
  for (let v: string | null = target; v !== null; v = parent[v]) path.push(v);
  return path.reverse();
}

export function demo(): string[] {
  const g: AdjacencyList = {
    A: ["B", "C"],
    B: ["A", "D"],
    C: ["A", "D", "E"],
    D: ["B", "C", "F"],
    E: ["C", "F"],
    F: ["D", "E"],
    G: [], // not connected to anything
  };
  const { order, dist } = bfs(g, "A");
  return [
    `visit order from A: ${order.join(" → ")}`,
    `distances: ${Object.entries(dist).map(([v, d]) => `${v}=${d}`).join(", ")}`,
    `shortest path A → F: ${shortestPath(g, "A", "F")?.join(" → ")}`,
    `path A → G: ${shortestPath(g, "A", "G") ?? "unreachable"}`,
  ];
}

When to use it

Use it when

  • You need the shortest path in number of steps in an unweighted graph.
  • You want everything within k hops of a vertex.
  • You're exploring level by level: org charts, dependency layers, crawling a site to a fixed depth.
  • Checking if two vertices are connected, or whether a graph is bipartite.

Avoid it when

  • Edges have different costs: use Dijkstra's algorithm.
  • You need to explore deep paths first, detect cycles in a directed graph, or produce a topological order: use depth-first search.
  • The graph is extremely wide and memory is tight: DFS or iterative deepening uses less memory.

Pitfalls

  • Marking visited when dequeuing instead of when enqueuing, which lets the same vertex enter the queue many times.
  • Using an array's shift() as a queue in hot loops: it's O(n) in many languages. Use a real queue or a moving head index.
  • Forgetting disconnected parts: one BFS only reaches vertices connected to the start. Loop over all vertices to cover the whole graph.
  • Applying it to weighted graphs, where fewest edges isn't the cheapest path.

Alternatives

Depth-first search

Choose it when you need to go deep first: cycle detection, topological sort, backtracking, or lower memory.

Dijkstra's shortest path

Choose it when edges have non-negative weights and you need the cheapest path.

A* search

Choose it when you search toward one known target and have a good estimate of the remaining distance, such as on a map.