Graph Representation
Adjacency matrices
A simple directed graph with vertices and no loops or parallel edges has at most edges; a simple undirected graph has at most . An adjacency matrix G[N][N] expresses vertex relationships directly.
For an unweighted graph, an entry is 1 when the edge exists and 0 otherwise.
| A | B | C | D | E | |
|---|---|---|---|---|---|
| A | 0 | 1 | 0 | 1 | 0 |
| B | 1 | 0 | 1 | 0 | 0 |
| C | 0 | 1 | 0 | 1 | 1 |
| D | 1 | 0 | 1 | 0 | 0 |
| E | 0 | 0 | 1 | 0 | 0 |
The diagonal is 0 for the simple graphs discussed here because self-loops are excluded. An undirected graph's adjacency matrix is symmetric: if A connects to B, B connects to A.
A directed graph's matrix need not be symmetric. A may reach B directly without a reverse edge.
| A | B | C | D | |
|---|---|---|---|---|
| A | 0 | 1 | 1 | 0 |
| B | 0 | 0 | 0 | 0 |
| C | 0 | 0 | 0 | 1 |
| D | 0 | 1 | 1 | 0 |
For a weighted network, store the edge's weight in the corresponding entry.
| A | B | C | D | E | F | |
|---|---|---|---|---|---|---|
| A | 5 | 2 | ||||
| B | 4 | |||||
| C | 9 | |||||
| D | 7 | 3 | ||||
| E | 1 | |||||
| F | 1 | 8 |
For distinct vertices with no edge, use rather than 0. When initializing shortest-path distances, set the diagonal to 0.
Advantages:
-
Simple and intuitive.
-
Fast lookup of whether two vertices are adjacent.
-
Convenient degree calculations. In a directed graph, outgoing edges determine outdegree and incoming edges determine indegree.
Disadvantages:
-
Sparse graphs waste space on many unused entries. Dense graphs, especially complete ones, use the matrix more effectively.
-
Counting edges in a sparse graph requires scanning many entries.
KNOWLEDGE QUIZ
Adjacency lists
Adjacency lists address the matrix's space cost. Each vertex heads a linked list of the neighboring vertices it can directly reach. For sparse graphs, this uses much less storage than a matrix.
Three storage views of the same graph
Unlock the complete interactive lab, deeper explanations, and curated reference answers.
Scanning a vertex's list finds its outgoing neighbors. The reverse question—who can reach this vertex—is less convenient.
A reverse adjacency list stores the vertices that directly reach each vertex instead.
Maintaining both lists separately is cumbersome.
An orthogonal, or cross-linked, list combines the outgoing and incoming chains.
KNOWLEDGE QUIZ
Represent directed edges as a matrix and lists
Vertices are ordered A, B, C, D; edges are A→B, A→D, C→A, C→D, D→B. Draw the graph, its adjacency matrix with source rows, and both outgoing and incoming lists. Explain B’s empty outgoing list and two incoming neighbors.