Explore the network.
Use adjacency lists and a queue to explore a network without revisiting nodes forever.
01 Model 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.
A vertex is discovered once, and the queue explores increasing edge distance.
02 State the strategy
Read the steps independently of syntax. Explain what each step preserves before translating it into code.
ENQUEUE the start and mark it discovered
DEQUEUE the next vertex
DISCOVER and enqueue unseen neighbours
RECONSTRUCT the route through parent linksDiscover A and put it in the queue.
03 Make it concrete
The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.
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']
- 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 Count the cost
O(V + E) on adjacency lists
O(V) traversal state
Bounds refer to the shown implementation and exclude printed output unless stated. n is input size; V and E are graph vertices and edges.
05 Your next move
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"))06 Check your reasoning
When does BFS find a shortest path?
Understand it. Then own it.
Can you explain the invariant, trace an edge case, and defend the cost model? Log the experiment when the reasoning makes sense.