RareProgramming
Fill the five gaps in the BFS function that finds a shortest path between distinct vertices.
Short answer
set() → deque → visited → end → path + [neighbor]Exercise
deque · end · path + [neighbor] · set() · visited
def bfs_shortest_path(graph, start, end):
visited = ___
queue = ___([(start, [start])])
while queue:
vertex, path = queue.popleft()
if vertex in ___:
continue
visited.add(vertex)
for neighbor in graph[vertex]:
if neighbor == ___:
return path + [neighbor]
queue.append((neighbor, ___))
return None
Solution
The queue stores each vertex with its path. The visited set prevents repeated expansion.
from collections import deque
def bfs_shortest_path(graph, start, end):
visited = set()
queue = deque([(start, [start])])
while queue:
vertex, path = queue.popleft()
if vertex in visited:
continue
visited.add(vertex)
for neighbor in graph[vertex]:
if neighbor == end:
return path + [neighbor]
queue.append((neighbor, path + [neighbor]))
return None
Each queue entry pairs a vertex with its current path. Removing from the left and appending on the right processes paths by edge count, so first reaching the target is shortest in an unweighted graph. Extending a copy of the path keeps the original intact for the other neighbours.
A → B → D; A → C → E → D. [A] → [A, B] → [A, B, D].
Platforms
- MAXIMUM
