Graph BFS Shortest Path Unweighted Typed

Find the shortest path in an unweighted typed graph using BFS with a predecessor map for path reconstruction.

TypescriptData Fetching

Code

typescriptsnippet
16 lines
function bfsShortestPath(graph: Map<string, string[]>, start: string, end: string): string[] | null {
  if (start === end) return [start];
  const queue: string[] = [start];
  const visited = new Set([start]);
  const parent = new Map<string, string>();
  while (queue.length) {
    const node = queue.shift()!;
    for (const neighbor of graph.get(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 the snippet works

Count the function bfsShortestPath as the entire surface area of Graph BFS Shortest Path Unweighted Typed.

The structure is a loop within a loop: while (queue.length) outside, for (const neighbor of graph.get(node) ?? []) inside.

A fresh value is allocated for the result; the arguments stay untouched.

Caveats

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

Applying it

Signature: function bfsShortestPath(graph: Map<string, string[]>, start: string, end: string)

Statements that matter

for (const neighbor of graph.get(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);
}
const parent = new Map<string, string>();
if (start === end) return [start];

Interactive Tools for This Topic

FAQ

Does `bfsShortestPath` modify its input?
No mutation happens — the function reads its input and returns a new value.
Is a package install part of the setup?
No. Installation is unnecessary because only built-in APIs are used. The file defines `bfsShortestPath` at load time.