Graph BFS Shortest Path Unweighted (JavaScript)

Find the shortest path in an unweighted graph using breadth first search with a predecessor map for path reconstruction.

JavascriptData Fetching

Code

javascriptsnippet
22 lines
function bfsShortestPath(graph, start, end) {
  if (start === end) return [start];
  const queue = [start];
  const visited = new Set([start]);
  const parent = new Map();
  while (queue.length) {
    const node = queue.shift();
    for (const neighbor of graph[node] || []) {
      if (visited.has(neighbor)) continue;
      visited.add(neighbor);
      parent.set(neighbor, node);
      if (neighbor === end) {
        const path = [end];
        let cur = end;
        while (parent.has(cur)) { cur = parent.get(cur); path.unshift(cur); }
        return path;
      }
      queue.push(neighbor);
    }
  }
  return null;
}

How it works

Count the function bfsShortestPath as the entire surface area of Graph BFS Shortest Path Unweighted (JavaScript).

The nesting pairs while (queue.length) with for (const neighbor of graph[node] || []) — the inner runs once per outer step.

The return value is newly constructed — inputs are never handed back.

Watch out for

  • The guard start === end short-circuits the flow with an early return when its condition holds.

Applying it

The main signature reads function bfsShortestPath(graph, start, end)

Statements that matter

if (start === end) return [start];
const visited = new Set([start]);
const parent = new Map();

Interactive Tools for This Topic

FAQ

Does `bfsShortestPath` modify its input?
The input survives unchanged; what you get back is a newly constructed value.
Do I need to install anything before running this?
No — every API used here ships with the language runtime, so there is nothing to install. The file defines `bfsShortestPath` at load time.