Breadth-First Search

CSE 241 Algorithms and Data Structures
11/5/2015
Breadth-First Search
Given a directed graph G = (V, E) and a starting vertex s, BFS computes the minimum number of edge
traversals required to reach each vertex v ∈ V from s. It stores both this distance and a path from s to each
v composed of parent pointers from each vertex to the previous one in the path.
The queue Q used by BFS is a simple FIFO. The algorithm runs in time O(m + n) (Θ(m + n) if G is
connected).
1
BFS(G = (V, E), s)
for u ∈ V do
u.visited ← false
u.distance ← ∞
u.parent ← null
. initialization
s.visited ← true
s.distance ← 0
Q.enqueue(s)
. start from s
while Q is not empty do
u ← Q.dequeue()
for v ∈ Adj[u] do
if not v.visited
v.visited ← true
v.distance ← u.distance + 1
v.parent ← u
Q.enqueue(v)
For our running time analysis, note first that this implementation enqueues each vertex when it is first
uncovered, eventually dequeues and processes it, and then never touches it again except perhaps to check its
visited flag. The enqueueing and dequeueing therefore takes time O(n). The processing involves following
every edge out of every vertex exactly once; we can account the (constant) time spent checking a visited
flag to the edge that cause the check. Hence, the processing takes time O(m). The initialization code is also
O(n), so the total running time is thereforeO(m + n)
2