Essential Data Structures home

Graph

A set of nodes joined by edges. The nodes are the things, and the edges are the relationships between them. Almost every network you use is a graph underneath.

A B C D E
Illustration: five nodes and five edges. D connects to B, C, and E, and you can reach every node from A by following the edges.

What it is

A graph holds a set of nodes, also called vertices, and a set of edges that join pairs of nodes. An edge says two nodes are related. That is all a graph is, and it is enough to describe roads between cities, friendships between people, links between web pages, and dependencies between pieces of software.

Edges can carry extra meaning. In a directed graph, each edge has a direction, like a one-way street or a follow on a social network. In an undirected graph, an edge works both ways, like a friendship. Edges can also carry weights, numbers that say how expensive or how long a connection is, which is what makes shortest-path problems possible.

A graph is not a container with one natural order. Nodes have no first or last, only neighbors. That is the point: a graph is for data where the relationships matter more than any ordering.

How it works

There are two standard ways to store a graph. An adjacency list keeps, for each node, a list of its neighbors. It is compact, using space proportional to the number of nodes plus the number of edges, and it is fast at listing neighbors. An adjacency matrix keeps a table with a row and a column for every node, and marks the cells where an edge exists. It answers the question "are these two nodes connected?" instantly, but it takes space proportional to the square of the number of nodes, which is wasteful when edges are few.

Most work on a graph is a traversal, a walk that visits nodes by following edges. Breadth-first search fans out level by level, visiting the nearest nodes first, and it finds shortest paths when every edge costs the same. Depth-first search dives down one path as far as it can before backtracking, and it is the natural way to find cycles and connected groups. Both visit each node and each edge once when the graph is stored as an adjacency list.

Complexity

OperationAverageWorst case
Check whether two nodes are connected (adjacency list)O(degree)O(V)
Check whether two nodes are connected (adjacency matrix)O(1)O(1)
Add an edgeO(1)O(1)
Remove an edge (adjacency list)O(degree)O(V)
Remove an edge (adjacency matrix)O(1)O(1)
List a node's neighbors (adjacency list)O(degree)O(V)
List a node's neighbors (adjacency matrix)O(V)O(V)
Visit every node and edge once, BFS or DFS (adjacency list)O(V + E)O(V + E)
Visit every node and edge once, BFS or DFS (adjacency matrix)O(V²)O(V²)

V is the number of nodes, E is the number of edges, and degree is the number of edges touching one node. An adjacency list uses O(V + E) space, and an adjacency matrix uses O(V²) space.

When to use it, and when not to

Use a graph when the relationships between items are the data: maps and routes, social networks, dependencies, recommendation systems, and anything you need to search for a path through. If you only need to look things up by key, store them in order, or hold them in a line, a hash table, a tree, or a queue is simpler and faster.

Do not use a graph when the data has no meaningful connections. The extra machinery buys nothing if every item stands alone. And pick the representation to match the question you ask most: an adjacency list when you walk neighbors and the graph is sparse, an adjacency matrix when you test connections constantly and the graph is dense.

Where you meet it

Everywhere a network is involved. A map app runs shortest-path search over a graph of roads and junctions. A social network is a graph of people and friendships, and "people you may know" is a walk two edges out from you. Web search treats pages as nodes and links as edges. Build tools and package managers use graphs to work out what depends on what, and whether the dependencies form a cycle that can never be satisfied.

In Python

from collections import deque

# An adjacency list: each node maps to the nodes it connects to
graph = {
    "A": ["B", "C"],
    "B": ["A", "D"],
    "C": ["A", "D"],
    "D": ["B", "C", "E"],
    "E": ["D"],
}

def breadth_first(graph, start):
    seen = {start}
    order = []
    queue = deque([start])
    while queue:
        node = queue.popleft()
        order.append(node)
        for neighbor in graph[node]:
            if neighbor not in seen:
                seen.add(neighbor)
                queue.append(neighbor)
    return order

print(breadth_first(graph, "A"))  # ['A', 'B', 'C', 'D', 'E']
print(graph["D"])                 # neighbors of D: ['B', 'C', 'E']

In short: a graph stores relationships, not order. Nodes and edges describe the connections, and walking the edges is how you search, route, and recommend.

Sources

← Home