Python Language Breadth First Search


Example

The Deque is the only Python data structure with fast Queue operations. (Note queue.Queue isn't normally suitable, since it's meant for communication between threads.) A basic use case of a Queue is the breadth first search.

from collections import deque

def bfs(graph, root):
    distances = {}
    distances[root] = 0
    q = deque([root])
    while q:
        # The oldest seen (but not yet visited) node will be the left most one.
        current = q.popleft()
        for neighbor in graph[current]:
            if neighbor not in distances:
                distances[neighbor] = distances[current] + 1
                # When we see a new node, we add it to the right side of the queue.
                q.append(neighbor)
    return distances

Say we have a simple directed graph:

graph = {1:[2,3], 2:[4], 3:[4,5], 4:[3,5], 5:[]}

We can now find the distances from some starting position:

>>> bfs(graph, 1)
{1: 0, 2: 1, 3: 1, 4: 2, 5: 2}

>>> bfs(graph, 3)
{3: 0, 4: 1, 5: 1}