A Breadth-first search algorithm is often used for traversing/searching a tree/graph data structure.
Here, we will learn to implement BFS Algorithm for a graph.
BFS for a graph is almost similar to BFS of a tree. There is only one difference here, unlike trees graphs may contain cycles, so it may happen that we come across the same vertex again and again. A vertex needs to be processed only once, so to avoid this situation we will use an array to keep track of the state of the vertex.
For example, in the following graph, suppose we start traversing from vertex A. When we come to vertex B, we look for all adjacent vertices of it. A is also an adjacent vertex of B. If we don't keep track of the visited vertices, then A will be processed again and again, hence this will become a non-terminating process.
Description:
In this algorithm we need to discover vertices in order of distance from the source vertex. This breadth first search algorithm works for both directed and undirected graphs.
Data Structures Used:
- state[u]: Provides the colour status of a node during the BFS operation.
- If state[u] = 1, then the node has not been discovered yet.
- If state[u] = 0, then the node has been discovered but not processed yet.
- If state[u] = 0, then the node has been processed.
- distance[u]: Stores the distance of a vertex from the source vertex S
- parent[u]: Stores the parent information
Procedure:
BFS(G, s)
#Initialize all the vertex except the source vertex
#V[graph] – list of nodes in the graph
for each vertex u ε V [Graph] - {s}
do state[u] = 1
distance[u] = 'inf'
parent[u] = nil
#Initialize the source vertex
state[s] = 0
distance[s] = 0
parent[s] = nil
#Create an empty Queue and an array arr to store the result
queue = []
arr = []
#Insert the source vertex in the queue
Enqueue(queue, s)
#loop until queue is empty
while queue
do u
Python Code for Breadth First Search for a Graph
Input:
Input format:
Output:
Output Format: Breadth first traversal starting from source node
need an explanation for this answer? contact us directly to get an explanation for this answer