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.
Code
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 === endshort-circuits the flow with an earlyreturnwhen 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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.