BFS explores a graph layer by layer, so the first time it reaches a vertex is along a shortest path. Track dist[v] and parent[v] while exploring, then walk parents back from the target to reconstruct the route.

Algorithm

On the canonical graph from graph-adjacency-list, the shortest path from 1 to 6 is [1, 2, 4, 5, 6] with distance 4. The path is rebuilt from parent: 6 -> 5 -> 4 -> 2 -> 1, reversed.

Basic Implementation

basic.js
const adj = new Map([
    [1, [2, 3]],
    [2, [1, 4]],
    [3, [1, 4]],
    [4, [2, 3, 5]],
    [5, [4, 6]],
    [6, [5]],
]);

const src = 1;
const dst = 6;
const dist = new Map([[src, 0]]);
const parent = new Map([[src, null]]);
const queue = [src];
while (queue.length > 0) {
    const v = queue.shift();
    for (const nb of adj.get(v)) {
        if (!dist.has(nb)) {
            dist.set(nb, dist.get(v) + 1);
            parent.set(nb, v);
            queue.push(nb);
        }
    }
}

const path = [];
let node = dst;
while (node !== null) {
    path.push(node);
    node = parent.get(node);
}
path.reverse();
console.log(JSON.stringify(path));
console.log(dist.get(dst));

Complexity

  • Time: O(V + E)
  • Space: O(V)

Implementation notes

  • JavaScript: a dist Map doubles as the visited check (a vertex is discovered once dist has it), and parent records the predecessor; queue.shift() dequeues in FIFO order.
  • The replay shows dist, parent, and the queue filling in, then the reconstructed path, matching the lesson spec.
layers equal distance BFS order equals distance in an unweighted graph.