ENع
←Lists vs matrices
Lesson 19 · Graph algorithms

Adjacency lists and adjacency matrices

14 min9 steps5 questionsIntermediate
About this lesson

The Software lesson "Graphs" shows that a graph can be stored as an adjacency list or an adjacency matrix. This lesson measures the difference. Build both from the same edge list of a 5-vertex directed graph, then ask each the same questions and count the reads: one for an edge check in the matrix, up to deg(u) in the list, V + E against V² to visit every edge. The Software lesson "Graph search: BFS and DFS" and the Maths lesson on graph theory supply the walks and the vocabulary used here.

You'll learn to

Tick what you feel confident about. These self-checks do not affect your lesson score.

Fig 19 · Interactive
01 / 09

One graph, two shapes

A directed graph: 5 vertices numbered 0 to 4 and 6 one-way edges, such as 3 → 4. Python receives it as an edge list of pairs. Algorithms need a shape they can ask questions of quickly: a list per vertex, or a grid.

edges = [(0, 1), (0, 2), (1, 2), (2, 3), (3, 1), (3, 4)]
V = 5, E = 6

out-degree deg(u) = edges leaving u:
  deg(0) = 2
  deg(1) = 1
  deg(2) = 1
  deg(3) = 2
  deg(4) = 0
sum of out-degrees = 6 = E
Loading figure…
or ← →
Read the lesson step by step
  1. One graph, two shapes

    A directed graph: 5 vertices numbered 0 to 4 and 6 one-way edges, such as 3 → 4. Python receives it as an edge list of pairs. Algorithms need a shape they can ask questions of quickly: a list per vertex, or a grid.

    edges = [(0, 1), (0, 2), (1, 2), (2, 3), (3, 1), (3, 4)]
    V = 5, E = 6
    
    out-degree deg(u) = edges leaving u:
      deg(0) = 2
      deg(1) = 1
      deg(2) = 1
      deg(3) = 2
      deg(4) = 0
    sum of out-degrees = 6 = E
  2. Build the adjacency list

    Start with one empty Python list per vertex. For each edge (u, v), append v to adj[u]. Six edges, six appends: adj[3] ends up as [1, 4]. Each directed edge is stored once, in the list of the vertex it leaves.

    adj = [[] for _ in range(V)]
    for u, v in edges:
        adj[u].append(v)      # amortised O(1)
    
    adj[0] = [1, 2]
    adj[1] = [2]
    adj[2] = [3]
    adj[3] = [1, 4]
    adj[4] = []
  3. Build the adjacency matrix

    The matrix starts as a 5 × 5 grid of zeros: 25 cells, made before any edge is read. Then each edge (u, v) sets mat[u][v] = 1. Row u shows where u’s edges go; column v shows where v’s edges come from.

    mat = [[0] * V for _ in range(V)]
    for u, v in edges:
        mat[u][v] = 1
    
          col 0 1 2 3 4
    row 0      0 1 1 0 0
    row 1      0 0 1 0 0
    row 2      0 0 0 1 0
    row 3      0 1 0 0 1
    row 4      0 0 0 0 0
  4. Count the space

    The list holds 5 heads plus 6 entries: V + E = 11 slots. The matrix holds V × V = 25 cells, even with no edges. Lists grow with the edges; the matrix grows with the square of the vertices.

    list:   V + E = 5 + 6 = 11 slots     Θ(V + E)
    matrix: V × V = 5 × 5 = 25 cells     Θ(V²)
    
    cells holding 1: 6 of 25
  5. Edge check: the matrix

    Ask: is there an edge from 3 to 4? The matrix goes straight to row 3, column 4 and reads one cell. It holds 1, so yes. One read, however big the graph: O(1) time.

    >>> mat[3][4] == 1
    True
    
    reads: 1   (index row, index column)
    time: O(1)
  6. Edge check: the list

    The list must search. Python’s in walks adj[3] from the left: 1, no; 4, yes. That took 2 reads. At worst it reads every entry, so the cost is O(deg(u)), where deg(u) counts the edges leaving u.

    >>> 4 in adj[3]
    True
    
    adj[3] = [1, 4]
      read slot 0: 1   no
      read slot 1: 4   yes, stop
    reads: 2   time: O(deg(3)) = O(2)
  7. Where does 3 lead?

    Now list every vertex 3 points to. The list hands over adj[3] = [1, 4]: 2 reads. The matrix must read all 5 cells of row 3 to find its two 1s. That is O(deg(u)) against O(V).

    >>> adj[3]
    [1, 4]
    >>> [v for v in range(V) if mat[3][v]]
    [1, 4]
    
    list reads:   2   O(deg(u))
    matrix reads: 5   O(V)    row 3 = 0 1 0 0 1
  8. Visit every edge

    BFS and DFS ask that question for every vertex. With lists that is 5 heads plus 6 entries: 11 reads, O(V + E). With the matrix it is every cell: 25 reads, O(V²), even when most cells are 0.

    for u in range(V):
        for v in adj[u]: ...            # list
    for u in range(V):
        for v in range(V):
            if mat[u][v]: ...           # matrix
    
    list:   V + E = 11 reads   Θ(V + E)
    matrix: V²    = 25 reads   Θ(V²)
  9. Sparse or dense?

    Pick by density. A graph with 1,000 vertices and 3,000 edges needs a 1,000,000-cell matrix that is almost all zeros, but only 4,000 list slots. When E is close to V², or edge checks dominate, choose the matrix.

    V = 1,000, E = 3,000
    list:   V + E = 4,000 slots
    matrix: V²    = 1,000,000 cells (0.3% hold a 1)
    
    sparse (E much less than V²): adjacency lists
    dense (E close to V²), many edge checks: matrix

Quiz Unlocks after the last step.