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

snippet
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;
}