Breadth-first search (BFS) is an algorithm used for graph traversal on graphs or tree data structures. BFS explores all the vertices at the current level before moving to the next level. It can be easily implemented using data structures such as queues or linked lists to maintain the exploration order.
The breadth-first search has a wide range of applications, e.g., web crawlers can use BFS to build an index. It starts from a source page and follows links, ensuring comprehensive coverage. It can also help find people within a given distance from a person up to a specified level on social networking websites.
Let’s discuss the algorithm for the BFS:
The following slides depict the flow of BFS in detail:
The following code example implements the BFS in Python.
graph = {'A' : ['B','C'],'B' : ['D', 'E'],'C' : ['F'],'D' : [],'E' : ['F'],'F' : []}visited = [] # List to keep track of visited nodes.queue = [] #Initialize a queuedef bfs(visited, graph, node):visited.append(node)queue.append(node)while queue:s = queue.pop(0)print (s, end = " ")for neighbour in graph[s]:if neighbour not in visited:visited.append(neighbour)queue.append(neighbour)# Driver Codebfs(visited, graph, 'A')
Lines 3–10: The illustrated graph is represented using an adjacency list. An easy way to do this in Python is to use a dictionary data structure, where each vertex has a stored list of its adjacent vertices or nodes.
Line 12: The visited
is a list that is used to keep track of visited nodes.
Line 13: The queue
is a list that is used to keep track of nodes currently in the queue.
Line 29: The arguments of the bfs
function are the visited
list, the graph
in the form of a dictionary, and the starting node A
.
Lines 15–26: The bfs
follows the algorithm described above:
visited
list and the queue
.Since all of the nodes are visited, the time complexity for BFS on a graph is ; where is the number of vertices or nodes and is the number of edges.
The space complexity of BFS is , where represents the number of vertices or nodes in the graph.
Free Resources