How to implement a ​breadth-first search in Python

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.

Algorithm

Let’s discuss the algorithm for the BFS:

  1. Start: Insert the starting node into a queue. Mark the starting node as visited.
  2. Explore: While the queue is not empty:
    • Remove a node from the queue and print its value
    • Insert all unvisited adjacent nodes of the removed node into the queue. Mark each adjacent node as visited to avoid revisiting.
  3. End: Repeat the process until the queue is empty.

The following slides depict the flow of BFS in detail:

Insert the starting node into a queue. Mark the starting node as visited.
1 of 12

Code example

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 queue
def 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 Code
bfs(visited, graph, 'A')

Explanation

  • 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:

    1. It checks and appends the starting node to the visited list and the queue.
    2. Then, while the queue contains elements, it keeps taking out nodes from the queue, appends the neighbors of that node to the queue if they are unvisited, and marks them as visited.
    3. This continues until the queue is empty.

Time complexity

Since all of ​the nodes are visited, the time complexity for BFS on a graph is O(V+E)O(V + E); where VV is the number of vertices or nodes and EE is the number of edges.

Space complexity

The space complexity of BFS is O(V)O(V), where VV represents the number of vertices or nodes in the graph.

Copyright ©2024 Educative, Inc. All rights reserved