Breadth-First Search
Breadth-First Search
Breadth-First Search
In the first stage, we visit all the vertices that are at the distance of one edge
away. When we visit there, we paint as "visited," the vertices adjacent to the start
vertex s - these vertices are placed into level 1.
In the second stage, we visit all the new vertices we can reach at the distance of
two edges away from the source vertex s. These new vertices, which are adjacent
to level 1 vertices and not previously assigned to a level, are placed into level 2,
and so on.
The BFS traversal terminates when every vertex has been visited.
Overall Strategy of BFS
Algorithm
To keep track of progress, breadth-first-search colors each vertex. Each vertex of the
graph is in one of three states:
1. Undiscovered;
3. Fully explored.
2. color [u] = Gray - for the "discovered but not fully explored" state, and
a. After initialization (paint every vertex white, set d[u] to infinity for each vertex u, and
set the parent of every vertex to be NIL), the source vertex is discovered in line 5. Lines 8-
9 initialize Q to contain just the source vertex s.
a
BFS simulation cont.
b. The algorithm discovers all vertices 1 edge from s i.e., discovered all vertices (w and
r) at level 1.
b c
BFS simulation cont.
d. The algorithm discovers all vertices 2 edges from s i.e., discovered all vertices (t, x,
and v) at level 2.
d e
f
BFS simulation cont.
g. The algorithm discovers all vertices 3 edges from s i.e., discovered all vertices (u and
y) at level 3.
g
h
BFS simulation cont.
i. The algorithm terminates when every vertex has been fully explored.