Graph BFS Shortest Path With Parent Tracking
Breadth-first search over adjacency maps that reconstructs the shortest unweighted path and reports distance or null when unreachable.
Code
export interface BfsResult {
path: string[];
distance: number;
}
export function shortestPath(
graph: ReadonlyMap<string, readonly string[]>,
start: string,
goal: string,
): BfsResult | null {
if (!graph.has(start)) throw new RangeError("start node is missing: " + start);
if (!graph.has(goal)) throw new RangeError("goal node is missing: " + goal);
if (start === goal) return { path: [start], distance: 0 };
const queue: string[] = [start];
const parents = new Map<string, string>();
const visited = new Set<string>([start]);
for (let head = 0; head < queue.length; head += 1) {
const node = queue[head];
for (const neighbor of graph.get(node) ?? []) {
if (visited.has(neighbor)) continue;
visited.add(neighbor);
parents.set(neighbor, node);
if (neighbor === goal) {
const path = [goal];
let current = goal;
while (current !== start) {
const parent = parents.get(current);
if (parent === undefined) return null;
path.push(parent);
current = parent;
}
path.reverse();
return { path, distance: path.length - 1 };
}
queue.push(neighbor);
}
}
return null;
}How the snippet works
Graph BFS Shortest Path With Parent Tracking is built around the function shortestPath.
The nesting pairs for (let head = 0; head < queue.length; head += 1) with for (const neighbor of graph.get(node) ?? []) — the inner runs once per outer step. RangeError is the guard’s signal — thrown at the branch, before any partial work happens.
The result is a fresh construction, so callers can keep their originals.
Points of care
- The guard
start === goalshort-circuits the flow with an earlyreturnwhen its condition holds.
Applying it
The main signature reads export function shortestPath( graph: ReadonlyMap<string, readonly string[]>, start: string, goal: string, )
shortestPath is what another module would consume; nothing else here is load-bearing for callers.
Statements that matter
if (!graph.has(start)) throw new RangeError("start node is missing: " + start);
if (!graph.has(goal)) throw new RangeError("goal node is missing: " + goal);
if (start === goal) return { path: [start], distance: 0 };
Interactive Tools for This Topic
FAQ
- Does `shortestPath` modify its input?
- No. The code builds and returns a new value and leaves the arguments untouched, so it is safe to call on shared or frozen data structures.
- How are precondition violations signaled?
- It throws `RangeError` before any real work runs, via the guard `start === goal` — handle it at the call site or let it propagate deliberately.
- What does the package manager see?
- An empty dependency file. The snippet imports nothing that needs fetching. The file defines `shortestPath` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.