8.2Representing Graphs: Adjacency Matrix and Adjacency Lists
Covers IGNOU MCS-208 §8.2
Before running any graph algorithm, the graph must be stored. There are two standard representations, and the choice affects both the memory used and the running time of the algorithms.
Adjacency matrix
For an undirected graph the matrix is symmetric: aij=aji, i.e. A=AT.
Adjacency lists
Comparison
Adjacency matrix
Adjacency lists
Space
O(n2)
O(n+e)
Is (u,v) an edge?
O(1)
O(deg(u))
List all neighbours of u
O(n)
O(deg(u))
Visit every edge
O(n2)
O(n+e)
Best for
Dense graphs (e close to n2)
Sparse graphs (e much smaller than n2), most real networks
Check Your Progress 1, Q3
For the directed graph of Figure 8.3 (edges 1→2, 1→3, 3→4, 4→1, 4→2) the matrix has aij=1 only for those ordered pairs; it is not symmetric:
1
2
3
4
1
0
1
1
0
2
0
0
0
0
3
0
0
0
1
4
1
1
0
0
For the undirected graph of Figure 8.4 (edges 1–2, 1–3, 1–4, 2–4, 3–4) the matrix is symmetric:
1
2
3
4
1
0
1
1
1
2
1
0
0
1
3
1
0
0
1
4
1
1
1
0
(The answers in §8.9 are correct, but the second matrix is labelled “Figure 8.3” instead of “Figure 8.4”.)
Lists: one list per vertex, O(n+e) space, fast neighbour enumeration.
Use a matrix for dense graphs, lists for sparse graphs.
For a weighted graph store weights, with ∞ (a large value) for “no edge”.
Practice questions
Answer on paper first, then check. The explanation matters more than the letter you chose.
Question 6 · short answer
Draw the adjacency matrix and the adjacency lists for the undirected graph with edges A–B, A–C, B–C, C–D, and state the space used by each.
Show worked answer
Matrix (order A, B, C, D): A: 0 1 1 0; B: 1 0 1 0; C: 1 1 0 1; D: 0 0 1 0 (symmetric). Lists: adj[A] = {B, C}; adj[B] = {A, C}; adj[C] = {A, B, D}; adj[D] = {C}. The matrix uses n2=16 cells; the lists use n=4 list heads plus 2e=8 entries.
MCA Online notes are made for reading on screen. Open https://mcastudy.online/mcs-208/graphs/representing-graphs-adjacency-matrix-and-adjacency-lists/ to read this page.