← All lessons

Graphs: breadth-first search

Sign in · Sign up

Lesson 12.9

A graph is a set of vertices and the links between them. It is handy to store one as a dictionary: every person gets a list of acquaintances.

from collections import deque

def bfs(graph, start):
    visited = set()
    queue = deque([start])

    while queue:
        node = queue.popleft()
        if node in visited:
            continue
        visited.add(node)
        print(node)
        ...                       # add the neighbours to the queue
  • the walk moves as a wave: the queue holds who to look at next;
  • visited prevents going in circles: acquaintances may know each other;
  • popleft() is BFS, while pop() is depth-first, a whole different story;
  • graph.get(node, []) — if a node has no acquaintances, nothing gets added.

The check gives the graph graph and the name start. Write bfs and print the vertices in walk order.

Hint

Breadth-first search keeps a queue (deque) and a visited set.

On every step take from the front (popleft), skip what has been seen, otherwise print the node, add it to visited and put all its neighbours at the end of the queue. Neighbours come from graph.get(node, []).