Data structures · 4 / 15 Theory

Graphs and traversals

A graph is a set of nodes (vertices) joined by edges. It models networks of all kinds: road maps, friendships in a social network, linked web pages, dependencies between tasks. If a tree is a graph with no cycles, a graph is the most general structure in this topic.

Representing a graph

The most convenient way in Python is a dictionary of neighbor lists: each node is a key and its value is the list of nodes it is connected to. In an undirected graph, each edge is recorded in both directions.

edges = [(1, 2), (1, 3), (2, 4), (3, 4), (4, 5)]

neighbors = {i: [] for i in range(1, 6)}
for a, b in edges:
    neighbors[a].append(b)
    neighbors[b].append(a)

print(neighbors)
# {1: [2, 3], 2: [1, 4], 3: [1, 4], 4: [2, 3, 5], 5: [4]}

Breadth-first traversal (BFS)

Breadth-first search visits the neighbors first, then the neighbors of the neighbors, and so on in growing "layers". It uses a queue (deque) and a set of already visited nodes so it does not go back.

from collections import deque

def bfs(neighbors, start):
    visited = {start}
    queue = deque([start])
    order = []
    while queue:
        current = queue.popleft()
        order.append(current)
        for v in sorted(neighbors[current]):
            if v not in visited:
                visited.add(v)
                queue.append(v)
    return order

print(bfs(neighbors, 1))   # [1, 2, 3, 4, 5]

The shortest path

Since BFS explores in layers, the first time it reaches a node it does so by the path with the fewest edges. By saving where each node comes from (parent) the path is rebuilt by going back from the target.

def shortest_path(neighbors, source, target):
    parent = {source: None}
    queue = deque([source])
    while queue:
        current = queue.popleft()
        if current == target:
            break
        for v in sorted(neighbors[current]):
            if v not in parent:
                parent[v] = current
                queue.append(v)
    if target not in parent:
        return None
    route = []
    while target is not None:
        route.append(target)
        target = parent[target]
    return route[::-1]

print(shortest_path(neighbors, 1, 5))   # [1, 2, 4, 5]

The parent dictionary does a double job: it points to where each node comes from and marks the visited ones. Try it in Shortest path in a graph.

Depth-first traversal (DFS)

Depth-first search follows one path to the end before trying another. It is the same as BFS but with a stack instead of a queue.

def dfs(neighbors, start):
    visited = {start}
    stack = [start]
    order = []
    while stack:
        current = stack.pop()
        order.append(current)
        for v in sorted(neighbors[current], reverse=True):
            if v not in visited:
                visited.add(v)
                stack.append(v)
    return order

print(dfs(neighbors, 1))   # [1, 2, 4, 5, 3]

Connected components

If the graph has groups of nodes that are not connected to each other, each group is a connected component. To count them, go through the nodes and, each time you find an unvisited one, launch a traversal (BFS or DFS) that marks its whole component. The number of traversals launched is the number of components. You practise it in Connected components.

def components(neighbors):
    visited = set()
    total = 0
    for start in neighbors:
        if start in visited:
            continue
        total += 1
        stack = [start]
        visited.add(start)
        while stack:
            current = stack.pop()
            for v in neighbors[current]:
                if v not in visited:
                    visited.add(v)
                    stack.append(v)
    return total

print(components(neighbors))                 # 1
print(components({1: [2], 2: [1], 3: []}))   # 2

BFS or DFS

BFSDFS
Helper structurequeue (deque)stack (list)
Orderby layers, from near to farone path to the end
Shortest path (no weights)yesnot necessarily
Connected componentsworksworks