To use a graph we must be able to visit its vertices systematically. Breadth first search explores it layer by layer.
Graph Representation
A graph G = (V, E) can be stored as an adjacency matrix (a V × V table of 0/1 or weights, taking Θ(V²) space and allowing edge tests in O(1)) or as adjacency lists (each vertex has a list of neighbours, taking Θ(V + E) space and suiting sparse graphs). The traversal times quoted below are for adjacency lists unless stated.
The Algorithm
Breadth first search (BFS) starts at a source vertex s, visits it, then visits all its neighbours, then all their unvisited neighbours, and so on: first the vertices at distance 1, then distance 2. It uses a queue (first in, first out). Mark s as visited and enqueue it. While the queue is not empty: remove a vertex u; for each neighbour v of u not yet visited, mark v visited, record its distance d[v] = d[u] + 1 and its parent u, and enqueue v. Marking when enqueuing ensures each vertex enters the queue once.
Analysis and Uses
Each vertex is enqueued and dequeued once, and each adjacency list is scanned once, so the time is Θ(V + E) with lists (Θ(V²) with a matrix) and the space is Θ(V). BFS produces a BFS tree; the tree path from s to v is a shortest path in number of edges in an unweighted graph. It is used for shortest paths in unweighted graphs, finding connected components, testing whether a graph is bipartite, level-order tree traversal, web crawling by depth and social-network "degrees of separation".
Definition: Breadth first search. A graph traversal that visits all vertices at distance k from the source before any at distance k + 1, using a queue, in Θ(V + E) time.
Table 3.5: BFS facts
| Item | Value | Remark |
|---|---|---|
| Data structure | Queue | First in, first out |
| Time (lists) | Θ(V + E) | Each vertex and edge once |
| Time (matrix) | Θ(V²) | Scanning each row |
| Gives | Shortest edge-count paths | In unweighted graphs |
Example 3.5: BFS trace
Problem: Graph edges: A-B, A-C, B-D, C-D, E-F, F-G. Run BFS from A, visiting neighbours in alphabetical order.
Solution:
- Queue [A]; visit A (distance 0).
- Remove A: enqueue B and C (distance 1). Queue [B, C].
- Remove B: enqueue D (distance 2). Remove C: D already visited. Remove D: no new vertices.
- E, F, G are not reachable from A.
Result: Order A, B, C, D with distances A 0, B 1, C 1, D 2; E, F, G unvisited.
from collections import deque
g = {"A": "BC", "B": "AD", "C": "AD", "D": "BC",
"E": "F", "F": "EG", "G": "F"}
def bfs(s):
dist, q = {s: 0}, deque([s])
while q:
u = q.popleft()
for v in g[u]:
if v not in dist:
dist[v] = dist[u] + 1
q.append(v)
return dist
print(bfs("A"))
Output
{'A': 0, 'B': 1, 'C': 1, 'D': 2}
Common mistakes
- Using a stack instead of a queue and getting depth first order.
- Marking a vertex visited only when it is dequeued, which can enqueue it many times.
- Expecting BFS distances to be shortest in weighted graphs.
- Forgetting to start BFS again from unvisited vertices in a disconnected graph.
Key takeaways
- BFS uses a queue and visits layer by layer.
- Time Θ(V + E) with adjacency lists; space Θ(V).
- It gives shortest paths in unweighted graphs.
- Mark vertices when they are enqueued.
Practice questions
- Which data structure does BFS use?
- What is the time complexity of BFS with adjacency lists?
- What does BFS compute in an unweighted graph?
Answers to the practice questions
- A queue.
- Θ(V + E).
- The fewest-edges distance from the source to each reachable vertex.
Sources
- Official BCA syllabus Design and Analysis of Algorithms, course code 26BCA404DS03, Unit III
