Breadth-first search (BFS) in Python, visualized step by step
PythonC
Starting from one vertex, visit everything one step away first, then two steps away, ring by ring. A queue does it: first in, first out; mark a vertex as seen when it enters, so it never enters twice.
bfs.py
from collections import deque
graph = {
"A": ["B", "C"],
"B": ["D"],
"C": ["D", "E"],
"D": ["F"],
"E": ["F"],
"F": [],
}
seen = {"A"}
q = deque(["A"])
order = []
while q:
v = q.popleft()
order.append(v)
for w in graph[v]:
if w not in seen:
seen.add(w)
q.append(w)
print(order)
How Breadth-first search (BFS) works
- Mark the start as seen and put it in the queue.
- Take the vertex v at the front of the queue and record it.
- For each neighbour of v not seen yet: mark it and add it to the back.
- When the queue is empty, every reachable vertex has been visited.
What to watch
The queueOut on the left, in on the right: vertices of the same level sit together.
seenMarked on entering the queue, so no vertex is queued twice.
FAQ
What is the time complexity of BFS?
O(V + E): each vertex is queued and taken out once, and each edge is looked at once.
BFS vs DFS?
BFS uses a queue and spreads out level by level: it finds the fewest steps (shortest paths in an unweighted graph). DFS uses a stack or recursion and goes deep first: good for components and backtracking.
Why mark a vertex when it is queued, not when it is taken out?
Marking it later lets several neighbours queue the same vertex, doing the same work many times.