Data Structures & Algorithms / Module 8: Graphs

Topic 8.2

BFS

Exploring a graph layer by layer with a queue: the route with the fewest edges.

9 min · intermediate

Watch: the search spreads like ripples on water: every place one road away first, then every place two away.

0queueBADCFAE
  • moving now
  • being checked
  • passed / marked
  • finished / the result
Step 1 of 8

Start at A, distance 0. The number under each place is how many roads it is from A.

BFS spreads like ripples on water: everything 1 road away first, then everything 2 away, and so on.

Like ripples in a pond

Throw a stone into a pond: the first ripple reaches everything close by, the second a little further. Nothing 3 away is touched before everything 2 away. The queue makes BFS work that way: nodes found earlier (closer) are processed earlier.

Code, for programmersBFS with distances and routes
function bfs(graph, start) {
  const dist = new Map([[start, 0]]);
  const from = new Map();                 // who found each node
  const queue = [start];
  for (let i = 0; i < queue.length; i++) {   // reading by index avoids shift(), which is O(n)
    const v = queue[i];
    for (const u of graph.get(v) ?? []) {
      if (dist.has(u)) continue;          // seen already: skip, or we loop forever on cycles
      dist.set(u, dist.get(v) + 1);
      from.set(u, v);
      queue.push(u);
    }
  }
  return { dist, from };
}

// route to a target: follow 'from' backwards
function route(from, target) {
  const path = [target];
  while (from.has(path[0])) path.unshift(from.get(path[0]));
  return path;
}

Why you must mark what you've seen

A tree has no cycles, so a traversal always ends. A graph does: A to B, B to C, C back to A. Without a "seen" mark, BFS would add A again, then B again, forever. Mark a node when it's added to the queue, not when it's taken out, so no node is queued more than once.

Where you meet it

  • "Friends of friends" and "people you may know": nodes 2 away.
  • The fewest moves in a grid game or a maze.
  • A web crawler exploring a site layer by layer from the home page.
  • Finding every service affected when one service goes down.

Quiz

  1. Which data structure makes BFS explore layer by layer?

  2. What happens if BFS doesn't mark seen nodes, in a graph with a cycle?

  3. On an unweighted graph, BFS gives…

0 of 3 answered.