breath first search
breath first search
Aim: To print all the nodes reachable from a given starting node in a digraph and
also to print the traversal using B.F.S method.
Theory: B.F.S proceeds in a concentric manner by visiting first all the vertices that
are adjacent to a starting vertex, then all unvisited vertices two edges apart from it,
and so on, until all the vertices in the same connected component as the starting
vertex are visited. If there still remain unvisited vertices, the algorithm has to be
restarted at an arbitrary vertex of another connected component of the graph.
ALGORITHM BFS(G)
Step 1: consider as no node visited initially.
for i = 0 to n-1 do
visited[i] = 0 // no node is visited
end for
Step 2: consider an empty queue and insert the source vertex to it and make it as visited.
f = r = k=0 //queue is empty
q[r] = source //insert source vertex into queue
visited[source] = 1 //add source to S (indicates source is visited)
Step 3: As long as the queue being empty, consider the next vertex to be visited
while (f <= r) // as long as queue is not empty
u = q[f], f = f + 1 // delete the vertex to be explored
Step 4: find the nodes adjacent to the source vertex considered, and make them as
visited.
for v 0 to n do // find the nodes v which are adjacent to u
if a[u][v] = 1 and v is not visited
visited[v] = 1 // add v to s indicates that v is visited now
q[r] = v, r = r + 1//insert new vertex into q for exploration
t[k,1] = u
t[k,2] = v
k=k+1 //output the pair (u,v)
end if
end for
end while