Graph BFS Shortest Path Unweighted (Python)
Find the shortest path in an unweighted graph using BFS with a predecessor dict for path reconstruction.
Code
from collections import deque
def bfs_shortest_path(graph, start, end):
if start == end:
return [start]
queue = deque([start])
visited = {start}
parent = {}
while queue:
node = queue.popleft()
for neighbor in graph.get(node, []):
if neighbor in visited:
continue
visited.add(neighbor)
parent[neighbor] = node
if neighbor == end:
path = [end]
cur = end
while cur in parent:
cur = parent[cur]
path.insert(0, cur)
return path
queue.append(neighbor)
return NoneWhat the code does
Graph BFS Shortest Path Unweighted (Python) comes down to the function bfs_shortest_path.
Repetition is confined to while queue — the rest of the file is straight-line.
Returns a newly built value, leaving the inputs as they were.
Applying it
Signature: def bfs_shortest_path(graph, start, end)
The surface worth importing is bfs_shortest_path; the helpers around it are private to the snippet.
Statements that matter
return [start]
queue = deque([start])
visited = {start}
Interactive Tools for This Topic
FAQ
- Does `bfs_shortest_path` 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.
- Are there third-party dependencies?
- No. The dependency list is empty; the code stays inside the standard library. The file defines `bfs_shortest_path` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.