4. BFS
Given a graph G = (V, E) and a distinguished source vertex s, breadth-
first search systematically explores the edges of G to "discover" every
vertex that is reachable from s.
It computes the distance (smallest number of edges) from s to each
reachable vertex.
It also produces a "breadth-first tree" with root s that contains all
reachable vertices.
For any vertex v reachable from s, the path in the breadth-first tree
from s to v corresponds to a "shortest path" from s to v in G, that is, a
path containing the smallest number of edges.
5. CONTI…
The algorithm works on both directed and undirected graphs.
Breadth-first search is so named because it expands the frontier
between discovered and undiscovered vertices uniformly across
the breadth of the frontier.
That is, the algorithm discovers all vertices at distance k from s
before discovering any vertices at distance k + 1.
6. BFS (G, S)
for each vertex u ϵ G.V – {s}
u.color = WHITE
u.d = ∞
u.π = NIL
s.color = GRAY
s.d = 0
s. π = NIL
Q = Ø
ENQUEUE (Q, s)
7. BFS (G, S)
while Q != Ø
u = DEQUEUE (Q)
for each v ϵ G.adj[u]
if v.color == WHITE
v.color = GRAY
v.d = u.d + 1
v. π = u
ENQUEUE (Q, v)
u.color = BLACK
8. CONTI…
Breadth first search in not naturally recursive. To understand the
differences and similarities, let us first consider the non-recursive
formulation of DFS algorithm.
Let stack be a data type allowing two operations PUSH and POP.
It handles elements in LIFO odder.
The function top denotes the first element at the top of the stack.