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 NoneReport a problem with this exampleOpens a pre-filled issue on GitHub.