Breadth-First Shortest Path in a Graph
Find the fewest hops between two nodes with breadth-first search, reconstructing the path and reporting when no route exists.
Code
from collections import deque
from typing import Dict, List, Optional
def shortest_path(
graph: Dict[str, List[str]], start: str, goal: str
) -> Optional[List[str]]:
if start == goal:
return [start]
queue = deque([start])
parents: Dict[str, Optional[str]] = {start: None}
while queue:
node = queue.popleft()
for neighbor in graph.get(node, []):
if neighbor in parents:
continue
parents[neighbor] = node
if neighbor == goal:
return reconstruct(parents, goal)
queue.append(neighbor)
return None
def reconstruct(parents: Dict[str, Optional[str]], goal: str) -> List[str]:
path = [goal]
while parents[path[-1]] is not None:
path.append(parents[path[-1]])
return list(reversed(path))What the code does
Breadth-First Shortest Path in a Graph comes down to the functions shortest_path and reconstruct.
Repetition is confined to while queue — the rest of the file is straight-line.
The return value is newly constructed — inputs are never handed back.
Using it
The primary signature is def shortest_path( graph: Dict[str, List[str]], start: str, goal: str ) -> Optional[List[str]]
Treat shortest_path as the API: import it, and ignore the supporting code.
Key statements
parents: Dict[str, Optional[str]] = {start: None}
def reconstruct(parents: Dict[str, Optional[str]], goal: str) -> List[str]:
path = [goal]
while parents[path[-1]] is not None:
path.append(parents[path[-1]])
return list(reversed(path))
def shortest_path(
graph: Dict[str, List[str]], start: str, goal: str
) -> Optional[List[str]]:
Interactive Tools for This Topic
Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.JSONPath TesterTest JSONPath expressions against JSON documents with dot notation, brackets, wildcards, and recursive descent.Levenshtein Distance CalculatorCompute the classic edit distance between two strings with a space-optimized DP and a normalized similarity percentage.Soundex EncoderEncode names into classic American Soundex codes with NARA rules for H/W separators, vowel boundaries, and zero padding.
FAQ
- Does `shortest_path` modify its input?
- The input survives unchanged; what you get back is a newly constructed value.
- Is there an install step between copy and run?
- No. Between copying and running there is nothing left to do. Every import resolves inside the standard library — `collections`, `typing`. The file defines `shortest_path`, `reconstruct` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.