Graph BFS Shortest Path Unweighted (TypeScript)
Find shortest path in unweighted graph using BFS with adjacency list for network traversal.
Code
export class Graph{private adj:Map<string,Set<string>>=new Map();addEdge(from:string,to:string):void{if(!this.adj.has(from))this.adj.set(from,new Set());if(!this.adj.has(to))this.adj.set(to,new Set());this.adj.get(from)!.add(to);this.adj.get(to)!.add(from);}shortestPath(start:string,end:string):string[]|null{if(!this.adj.has(start)||!this.adj.has(end))return null;const visited=new Set<string>([start]);const queue:[string,string[]][]=[[start,[start]]];while(queue.length>0){const[node,path]=queue.shift()!;if(node===end)return path;for(const neighbor of this.adj.get(node)??[]){if(!visited.has(neighbor)){visited.add(neighbor);queue.push([neighbor,[...path,neighbor]]);}}}return null;}}Inside the snippet
Count the class Graph as the entire surface area of Graph BFS Shortest Path Unweighted (TypeScript).
What to watch for
- The guard
node===endshort-circuits the flow with an earlyreturnwhen its condition holds.
Using it
Graph is what another module would consume; nothing else here is load-bearing for callers.
Interactive Tools for This Topic
JSONPath TesterTest JSONPath expressions against JSON documents with dot notation, brackets, wildcards, and recursive descent.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.SVG Path VisualizerParse SVG path d attributes (M/L/H/V/C/S/Q/T/A/Z), render a scaled wireframe preview with vertices and control handles, and compute bounding boxes.
FAQ
- What does the package manager see?
- An empty dependency file. The snippet imports nothing that needs fetching.
Report a problem with this exampleOpens a pre-filled issue on GitHub.