Python Breadth First Search (BFS) Algorithm

Breadth First Search (BFS) is a graph traversal algorithm that visits all the vertices of a graph in breadth-wise manner. It starts from the root node and visits all the neighbors at the current depth before moving on to the next level.

Here's a simple implementation of BFS in Python using an adjacency list to represent a graph:
from collections import deque

def bfs(graph, node):

    visited = []

    queue = deque([node])

    while queue:

        current_node = queue.popleft()

        if current_node not in visited:

            print(current_node, end=' ')


            queue.extend(graph[current_node] - set(visited))

graph = {

    'A': set(['B', 'C']),

    'B': set(['A', 'D', 'E']),

    'C': set(['A', 'F']),

    'D': set(['B']),

    'E': set(['B', 'F']),

    'F': set(['C', 'E'])


bfs(graph, 'A')

This code will produce the following output:


Note that the output order may vary depending on the implementation of the adjacency list and the order of neighbors in each node's list. The important thing is that all vertices are visited and processed in a breadth-first manner.