Breadth-first search
Explore an unweighted graph layer by layer and follow the queue as it changes.
queue = deque([start])discovered = {start}while queue: node = queue.popleft() for neighbor in graph[node]: if neighbor not in discovered: discovered.add(neighbor) queue.append(neighbor)Put the start node in the queue and mark it as discovered.
Explore nodes in layers
Start by marking the source and adding it to the queue. A queue removes the oldest waiting entry. When you remove a vertex, add its unvisited neighbors and mark them immediately so that two parents cannot enqueue the same vertex.
How it works
Draw a queue and a visited set beside the graph. Each time a neighbor is found, mark it visited before adding it to the queue. The first layer is one edge away, the second layer two edges away. This order lets the first visit give a shortest route when all edges count equally.
Relate order to distance
The queue processes all vertices one edge away before vertices two edges away. In an unweighted graph, BFS therefore finds the minimum number of edges needed to reach each reachable vertex. A traversal only covers the component containing its start when the graph is disconnected.
Account for work
With adjacency lists you visit each reachable vertex once and inspect each relevant edge a constant number of times. This gives O(V + E) worst-case time and O(V) extra space for visited marks and the queue.
Code example
from collections import deque
graph = {"A": ["B", "C"], "B": ["A", "D"], "C": ["A"], "D": ["B"]}
queue = deque(["A"])
seen = {"A"}
while queue:
vertex = queue.popleft()
print(vertex)
for neighbor in graph[vertex]:
if neighbor not in seen:
seen.add(neighbor)
queue.append(neighbor)Check your understanding
Starting at A, list visited vertices. Process each vertex’s neighbors alphabetically and treat the edges as undirected.
See the example and explanation
- Example 1
- Given
Edges A-B, A-C, B-D - Answer
A, B, C, D - Example 2
- Given
Vertices A, B, C. Edge B-C - Answer
A
For the first graph, A discovers B and C. Visiting B discovers D, which goes behind C. In the disconnected example B and C cannot be reached from A.