Graphs and Graph Representations: Lists, Matrices, Edges
Road maps, course prerequisites, links between web pages, friendships and software dependencies are all graphs. Before any graph algorithm can run, the graph has to be stored, and the choice of representation sets the cost of everything that follows. Examples use Python 3.10 or later and only the standard library.
Vocabulary
- A graph G = (V, E) is a set of vertices (or nodes) V and a set of edges E, each edge joining two vertices. By convention V and E also stand for the number of vertices and edges in complexity bounds such as O(V + E).
- In an undirected graph an edge {u, v} can be followed both ways (a friendship). In a directed graph an edge (u, v) goes from u to v only (a one-way street, or "u must come before v").
- A weighted graph attaches a number to each edge, such as a distance, a cost or a capacity. In an unweighted graph every edge counts the same.
- The degree of a vertex in an undirected graph is its number of edges. In a directed graph a vertex has an in-degree (edges arriving) and an out-degree (edges leaving). In an undirected graph the degrees add up to 2E, since each edge touches two vertices.
- A path is a sequence of vertices joined by edges. A cycle is a path that returns to its start. A directed graph with no cycles is a DAG (directed acyclic graph), the shape behind dependency ordering.
- A graph is sparse when E is close to V (each vertex has a few neighbors) and dense when E is close to V^2, the most it can be.
One graph, three representations
This undirected graph has five vertices and six edges. The program builds it in all three common forms and prints each one:
# An undirected graph with 5 vertices and 6 edges.
vertices = ["A", "B", "C", "D", "E"]
edges = [("A", "B"), ("A", "C"), ("B", "C"), ("B", "D"), ("C", "D"), ("D", "E")]
# 1. Edge list: just the pairs.
print("edge list:", edges)
# 2. Adjacency list: each vertex maps to its neighbors.
adj = {v: [] for v in vertices}
for u, v in edges:
adj[u].append(v)
adj[v].append(u) # undirected: store both directions
print("adjacency list:")
for v in vertices:
print(" ", v, adj[v])
# 3. Adjacency matrix: matrix[i][j] == 1 if there is an edge i-j.
index = {v: i for i, v in enumerate(vertices)}
matrix = [[0] * len(vertices) for _ in vertices]
for u, v in edges:
matrix[index[u]][index[v]] = 1
matrix[index[v]][index[u]] = 1
print("adjacency matrix:")
print(" ", " ".join(vertices))
for v in vertices:
print(" ", v, " ".join(str(x) for x in matrix[index[v]]))
# Is there an edge B-E? Degree of each vertex?
print("B-E edge?", matrix[index["B"]][index["E"]] == 1, "E" in adj["B"])
print("degrees:", {v: len(adj[v]) for v in vertices})
print("stored entries: list", sum(len(n) for n in adj.values()),
"matrix", len(vertices) ** 2)
edge list: [('A', 'B'), ('A', 'C'), ('B', 'C'), ('B', 'D'), ('C', 'D'), ('D', 'E')]
adjacency list:
A ['B', 'C']
B ['A', 'C', 'D']
C ['A', 'B', 'D']
D ['B', 'C', 'E']
E ['D']
adjacency matrix:
A B C D E
A 0 1 1 0 0
B 1 0 1 1 0
C 1 1 0 1 0
D 0 1 1 0 1
E 0 0 0 1 0
B-E edge? False False
degrees: {'A': 2, 'B': 3, 'C': 3, 'D': 3, 'E': 1}
stored entries: list 12 matrix 25
Edge list
The edges as a list of pairs (or triples with a weight). It takes O(E) space and is the simplest thing to read from a file. Answering "who are the neighbors of B?" means scanning every edge, O(E), so it is rarely what an algorithm works on directly. It suits algorithms that process edges in bulk, such as sorting all edges by weight in Kruskal's minimum spanning tree algorithm or relaxing every edge in Bellman-Ford.
Adjacency list
For each vertex, the list of its neighbors. In Python, a dict from vertex to list is the natural form. It takes O(V + E) space: one entry per vertex plus one per edge in a directed graph, or two per edge in an undirected one (the example stores 12 entries for 6 edges). Listing the neighbors of v takes O(degree of v), which is exactly what traversals need, so BFS and DFS run in O(V + E) on an adjacency list. Checking whether one particular edge u to v exists means scanning u's list, O(degree of u). If you need that check often, store each vertex's neighbors in a set instead of a list, which makes it O(1) on average.
Adjacency matrix
A V by V grid where entry [i][j] is 1 (or the edge weight) if there is an edge from i to j, and 0 (or a "no edge" marker) otherwise. Vertices need integer indices, hence the index dict. It takes O(V^2) space whatever the number of edges: 25 cells for this graph, of which only 12 are nonzero. The edge check is O(1): read one cell. But listing the neighbors of a vertex means reading its whole row, O(V), so a traversal on a matrix costs O(V^2). In an undirected graph the matrix is symmetric.
Costs side by side
| Question | Edge list | Adjacency list | Adjacency matrix |
|---|---|---|---|
| Space | O(E) | O(V + E) | O(V^2) |
| Is there an edge u to v? | O(E) | O(degree of u) | O(1) |
| List the neighbors of u | O(E) | O(degree of u) | O(V) |
| Visit every edge | O(E) | O(V + E) | O(V^2) |
| Add an edge | O(1) | O(1) | O(1) |
Directed and weighted graphs
For a directed graph, store each edge once, under the vertex it leaves. For a weighted graph, store (neighbor, weight) pairs, or a nested dict {u: {v: weight}} if you also want quick edge checks. This one-way road network keeps a list of (town, length) pairs per town and computes in-degrees and out-degrees:
# A directed, weighted graph: road lengths between towns, one way each.
roads = [("home", "mill", 4), ("home", "bridge", 1),
("bridge", "mill", 2), ("mill", "market", 5)]
graph = {}
for u, v, w in roads:
graph.setdefault(u, []).append((v, w)) # (neighbor, weight)
graph.setdefault(v, []) # make sure every vertex appears
for town, out_edges in graph.items():
print(town, "->", out_edges)
out_degree = {t: len(e) for t, e in graph.items()}
in_degree = {t: 0 for t in graph}
for u, v, w in roads:
in_degree[v] += 1
print("out:", out_degree)
print("in: ", in_degree)
home -> [('mill', 4), ('bridge', 1)]
mill -> [('market', 5)]
bridge -> [('mill', 2)]
market -> []
out: {'home': 2, 'mill': 1, 'bridge': 1, 'market': 0}
in: {'home': 0, 'mill': 2, 'bridge': 1, 'market': 1}
Note the setdefault(v, []) line: without it, a vertex with no outgoing edges (market) would be missing from the dict, and code that loops over graph would never see it. Forgetting isolated or sink vertices is a common source of wrong answers. This adjacency-list form, with weights, is the input to shortest-path algorithms such as Dijkstra's algorithm.
Which representation to use
- Sparse graph (most real graphs: road networks, dependency graphs, social graphs): use an adjacency list. A matrix would waste V^2 cells on mostly zeros; a graph with 100,000 vertices would need 10^10 cells.
- Dense graph, or a small one where you constantly ask "is u connected to v?": a matrix gives O(1) edge checks, and its V^2 cells are mostly used anyway. Algorithms that consider every pair of vertices, such as Floyd-Warshall for all-pairs shortest paths, are naturally written on a matrix.
- Edges arriving from a file, or an edge-centric algorithm: keep an edge list, and convert to an adjacency list when you need to traverse.
A grid or maze is a graph too, but you usually do not build it explicitly: each cell's neighbors are computed on the fly as the cells up, down, left and right.
With a graph stored, the first algorithms to learn are the two traversals; breadth-first and depth-first search uses the adjacency-list form built here.
Check yourself
- An undirected graph has 1,000 vertices and 3,000 edges. How many entries does its adjacency list hold, and how many cells does its matrix have? (6,000 entries; 1,000,000 cells.)
- Why does a BFS cost O(V^2) on a matrix even if the graph has few edges? (Finding each vertex's neighbors reads a whole row of V cells.)
- In the weighted example, what is the in-degree of
mill, and which edges give it? (2: fromhomeand frombridge.)