Graph Traversal Algorithm: Recapitulation
Graph Traversal Algorithm: Recapitulation
Recapitulation
AM
01-09-2014
Breadth First Search(BFS)
Breadth-first search is one of the simplest algorithms for searching a
graph
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.
Intuitively, the basic idea of the breath-first search is this:
send a wave out from sources.
The wave hits all vertices 1 edge froms. From there, the wave hits
all vertices 2 edges froms. Etc.
We use FIFO queue Q to maintain the wavefront: vis in Q if and only
if wave has hit vbut has not come out of vyet.
Strategy of BFS Algorithm
Breadth-first searchstarts at agivenvertex s, whichis at level
0.
In the first stage, we visit all the vertices that are at the
distanceof oneedgeaway, painted as visited areplaced in
level 1.
In the second stage, we visit all the new vertices. Thesenew
vertices, which are adjacent to level 1 vertices and not
previously assigned to alevel, areplaced into level 2, and so
on.
Strategy of BFS Algorithm
To keep track of progress, breadth-first-search colorseach
vertex. Each vertex of the graph is in one of three states:
Undiscovered;
Discovered but not fully explored; and
Fully explored.
The state of a vertex, u, is stored in a color variable as
follows:
color[u] =White - for the "undiscovered" state,
color [u] =Gray - for the "discovered but not fully explored"
state, and
color [u] =Black - for the "fully explored" state.
Algorithm: Breadth-First Search
Traversal
Example
Example: The following figure illustrates the
progress of breadth-first search on the
undirected sample graph.
Analysis
The while-loop in breadth-first search is executed at most |V|
times. The reason is that every vertex enqueuedat most once.
So, we have O(V).
The for-loop inside the while-loop is executed at most |E|
times if G is a directed graph or 2|E| times if G is undirected.
The reason is that every vertex dequeuedat most once and we
examine (u, v) only whenu is dequeued. Therefore, every edge
examined at most once if directed, at most twice if undirected.
So, we have O(E).
Therefore, the total running time for breadth-first search
traversal is O(V +E).