Explore the network.
Use adjacency lists and a queue to explore a network without revisiting nodes forever.
01 The idea
A graph represents vertices and edges. An adjacency list maps each vertex to its neighbours. Breadth-first search explores by distance from a starting vertex using a queue, making it suitable for shortest paths when every edge has equal cost. Record vertices as discovered when enqueuing them to avoid inserting the same vertex repeatedly.
02 The experiment
Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.
from collections import deque
def shortest_path(graph, start, goal):
queue = deque([start])
parent = {start: None}
while queue:
node = queue.popleft()
if node == goal:
path = []
while node is not None:
path.append(node); node = parent[node]
return list(reversed(path))
for neighbour in graph.get(node, []):
if neighbour not in parent:
parent[neighbour] = node
queue.append(neighbour)
return None
network = {"A": ["B", "C"], "B": ["D"], "C": ["D"], "D": []}
print(shortest_path(network, "A", "D"))['A', 'B', 'D']
03 Under the hood
- 1
The parent dictionary doubles as the discovered set and the information needed to reconstruct a path.
- 2
Queue order ensures all distance-one candidates are explored before distance-two candidates. When multiple shortest paths exist, neighbour order affects which one is returned.
- 3
With adjacency lists, traversal takes O(V + E) work over reachable vertices and edges. Weighted shortest paths need a different algorithm, such as Dijkstra’s for nonnegative weights.
04 Your turn, builder
Check that a disconnected destination returns None and that a start equal to the goal yields a one-vertex path.
Reveal one possible solution +
from collections import deque
def reachable(graph, start, goal):
queue, seen = deque([start]), {start}
while queue:
node = queue.popleft()
if node == goal: return True
for neighbour in graph.get(node, []):
if neighbour not in seen:
seen.add(neighbour); queue.append(neighbour)
return False
print(reachable({"A": []}, "A", "Z"))
print(reachable({"A": []}, "A", "A"))05 Check your signal
When does BFS find a shortest path?
Experiment. Logged.
When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.
Keep exploring
Go deeper with the official Python guide ↗.