BFS works best when there is a concept of layers or levels of neighborhoods in the aGraph we are dealing with. For example, when the connections of a person in LinkedIn are expressed as a graph, there are first-level connections and then there are second-level connections, which directly translate to the layers.
The BFS algorithm starts from a root vertex and explores the vertices in the neighborhood vertices. It then moves to the next neighborhood level and repeats the process.
Let's look at a BFS algorithm. For that, let's first consider the following undirected graph:
Let's start by calculating the immediate neighborhood of each vertex and store that in a list, called an adjacency list. In Python, we can use the dictionary data structure to store it:
graph={ 'Amin' : {'Wasim', 'Nick', 'Mike'},
'Wasim' : {'Imran', 'Amin'},
'Imran' : {'Wasim','Faras'},
'Faras' : {'Imran'},
'Mike' : {'Amin'},
'Nick' : {'Amin'}}
To implement it in Python, we proceed as follows.
We will first explain the initialization and then the main loop.