← All coursesDSA Foundations

Lesson 17 of 19

Graph traversal

Find a route between stations. Breadth-first search (BFS) uses a queue to explore every one-stop neighbor before moving to stations two stops away.

The first discovery gives the fewest hops

Breadth-first search uses a queue to visit a graph one distance layer at a time. Mark each neighbor as seen when it enters the queue so two stations cannot enqueue it twice. Remember which station first discovered it and you can reconstruct a shortest route in an unweighted graph.

Work through an example

A connects to B and C. Both B and C connect to D. Starting at A and checking B before C, which route to D gets recorded?

Step-by-step solution
  1. Visit A. Enqueue B and C, both one hop away. Record A as the parent of each.
  2. Visit B first. Discover D and record B as its parent. When C sees D, D is already marked.
  3. Follow the parents backward from D to B to A, then reverse the order. A → B → D takes two hops. A → C → D is equally short.
JavaScript example
const links = { A: ["B", "C"], B: ["A", "D"],
                C: ["A", "D"], D: ["B", "C"] };
const queue = ["A"];
const parent = new Map([["A", null]]);
for (let i = 0; i < queue.length; i++) {
  for (const next of links[queue[i]]) {
    if (parent.has(next)) continue;
    parent.set(next, queue[i]);
    queue.push(next);
  }
}
const route = [];
for (let at = "D"; at !== null; at = parent.get(at)) route.push(at);
route.reverse(); // ["A", "B", "D"]
DSA compiler

Try it yourself

Finish the animation to unlock this question.

BFS finds a shortest route by number of stops when…

Play Lantern Relay · Related exercise · Shortest paths with BFS · Take the end-of-stage challenge