Vocabulary
A graph G = (V, E) is a set of nodes (vertices) V and a set of edges E, each edge joining two nodes. We write V and E for their counts too. In this course nodes are numbered 0 … V − 1, which lets arrays indexed by node replace hash maps.
- Undirected edges are symmetric:
{u, v}connects both ways (friendships, roads you can drive both ways). Directed edgesu → vhave a direction (links, dependencies, one-way streets). - Weighted edges carry a number (distance, cost, capacity). Unweighted graphs treat every edge as cost 1.
- The degree of a node in an undirected graph is its number of edges. In a directed graph a node has an out-degree (edges leaving) and an in-degree (edges arriving). In an undirected graph the degrees add up to 2E, because each edge counts at both ends; in a directed graph the in-degrees add up to E, and so do the out-degrees.
- A path is a sequence of nodes joined by edges; a cycle is a path that returns to its start without reusing an edge. A directed graph with no directed cycle is a DAG.
- An undirected graph is connected if every node can reach every other one; otherwise it splits into connected components.
- A simple graph has no self-loops (
u → u) and no duplicate edges. The lab only accepts simple graphs, which keeps the drawings readable; multigraphs exist (two flights between the same cities) and need their edges stored individually.
A simple undirected graph has at most V(V − 1)/2 edges, a simple directed one at most V(V − 1). A graph is informally dense when E is close to that maximum (Θ(V²)) and sparse when E is much smaller, often Θ(V). Road networks, social networks and dependency graphs are sparse: a city connects to a handful of others, not to every city in the country.
Three ways to store the same graph
Take the undirected graph with V = 5 and edges 0–1, 0–2, 1–3, 2–3, 3–4.
Edge list: just the pairs.
(0,1) (0,2) (1,3) (2,3) (3,4)
Adjacency matrix: a V × V table with M[u][v] = 1 when there is an edge (or the weight, with
a marker such as ∞ for "no edge"). Undirected graphs give a symmetric matrix.
0 1 2 3 4
0 [ 0 1 1 0 0 ]
1 [ 1 0 0 1 0 ]
2 [ 1 0 0 1 0 ]
3 [ 0 1 1 0 1 ]
4 [ 0 0 0 1 0 ]
Adjacency lists: for each node, the list of its neighbours. Each undirected edge appears twice,
once in each endpoint's list; a directed edge u → v appears only in u's list.
0: 1 2
1: 0 3
2: 0 3
3: 1 2 4
4: 3
The lab on this page takes an edge list as input (one edge per line), builds adjacency lists from it, and shows them in its Text view, where each node's line ends with its neighbours. Toggle Directed edges and run the same edges again to see each edge disappear from one of its two lists. The lab itself runs breadth-first or depth-first search, which the next module covers; for now, watch how the search reads one adjacency list per visited node.
What each representation costs
With V nodes, E edges and deg(u) neighbours of u:
| Operation | Edge list | Adjacency matrix | Adjacency lists |
|---|---|---|---|
| Space | Θ(E) | Θ(V²) | Θ(V + E) |
| Is there an edge u–v? | O(E) | O(1) | O(deg(u)); O(1) expected with hash sets |
| Visit all neighbours of u | O(E) | O(V) | O(deg(u)) |
| Visit every edge | O(E) | O(V²) | O(V + E) |
| Add an edge | O(1) | O(1) | O(1) (append) |
| Remove an edge u–v | O(E) | O(1) | O(deg(u)) |
| Add a node | O(1) | O(V²) to rebuild (or reserve space) | O(1) amortized |
The neighbour row is the one that matters most, because nearly every graph algorithm is a loop of "take a node, look at all its neighbours". With lists, the whole loop over all nodes touches each list once: O(V + E) in total. With a matrix it reads V cells per node, O(V²), even if the graph has almost no edges. For a sparse graph with a million nodes and five million edges, that is the difference between a few million steps and 10¹² steps, and between tens of megabytes and a terabit-sized matrix (10¹² bits, about 125 GB).
Choosing
- Adjacency lists are the default: sparse graphs, traversals (BFS, DFS), topological sort, shortest paths with Dijkstra, anything that iterates neighbours.
- An adjacency matrix pays off when the graph is small or dense and the algorithm asks "is there an edge between these two?" constantly: Floyd–Warshall all-pairs shortest paths, transitive closure, some dynamic programming over subsets of a dozen nodes. A bit matrix (one bit per cell) cuts memory by 8× or more.
- An edge list suits algorithms that process edges as a whole, in some order: Kruskal's minimum spanning tree sorts the edge list; Bellman–Ford relaxes every edge in rounds. It is also the usual input and file format, which is why the lab and the code here start from one.
If edge lookups and neighbour iteration are both frequent, adjacency sets (a hash set per node) give expected O(1) lookups while keeping O(deg) iteration, at a higher constant cost and with no fixed neighbour order.
Building adjacency lists in four languages
All four implementations on this page contain the same builder: allocate one empty list per node, append both directions for an undirected edge, then sort every list.
| Language | Lists | Matrix |
|---|---|---|
| C# | List<int>[] (or List<List<int>>) |
bool[,] or int[,]; BitArray per row |
| Python | list[list[int]]; defaultdict(list) for non-integer node names |
list of lists (V lists of V entries; never [[0] * V] * V, which repeats one row V times) |
| Java | List<List<Integer>> of ArrayList |
boolean[][]; BitSet per row |
| C++ | std::vector<std::vector<int>> |
std::vector<std::vector<char>> or std::vector<std::bitset<N>> for a fixed N |
Two practical notes. Java's List<Integer> stores references to boxed integers, several times the
memory of an int[]; very large graphs often use a flat compressed layout instead: one array of
all neighbours concatenated and one array of start offsets per node (often called CSR). And when node
names are strings, map them to 0 … V − 1 once with a dictionary, then use arrays everywhere else.
Why sort the lists? Graph algorithms usually do not care in which order neighbours are visited, but their exact output does: BFS and DFS visit nodes in a different sequence if the lists are in a different order. Sorting fixes "smallest neighbour first" as the tie-break, so the lab, the fixture files and all four languages agree step for step. It costs O(E log E) once; production code often skips it.
Common mistakes
- Adding only one direction of an undirected edge, so the graph silently becomes directed.
- Building a matrix for a large sparse graph, then running out of memory or time.
- Assuming in-degree is stored. Adjacency lists give out-neighbours; in-degrees (or reverse lists) must be computed with one pass over all edges, as topological sort does.
- Aliasing rows when creating a matrix in Python with list multiplication.
- Mixing 0-based and 1-based node numbers between input and arrays.
Worked practice
1. Directed edges 0 → 1, 0 → 2, 2 → 1, 1 → 3. Write the adjacency lists and the in-degree of every node.
Answer
Lists: 0: 1 2; 1: 3; 2: 1; 3: (none). In-degrees: 0 has 0, 1 has 2 (from 0 and 2), 2 has 1, 3 has 1. They add up to 4 = E.
2. A social network has 10⁷ users with on average 200 friends each. Estimate the storage for an adjacency matrix and for adjacency lists of 4-byte integers.
Answer
Matrix: 10¹⁴ cells; even at one bit per cell that is about 12.5 TB. Lists: every user's list holds about 200 entries (each friendship appears in both friends' lists), so 10⁷ × 200 = 2 × 10⁹ entries × 4 bytes = 8 GB, plus per-list overhead. Lists win by more than three orders of magnitude.
3. Which representation would you use for an algorithm that, for every pair of nodes (i, j) and every middle node k, asks whether i → k and k → j are edges, on a graph with 300 nodes?
Answer
An adjacency matrix: the algorithm does V³ = 2.7 × 10⁷ edge lookups, each O(1) in a matrix, and the matrix has only 90,000 cells. This is the pattern of Floyd–Warshall and transitive closure.
Summary
- Graph vocabulary: directed or undirected, weighted, degree (in and out), path, cycle, component, simple, sparse and dense.
- Edge list: Θ(E) space, good for processing all edges; slow queries.
- Adjacency matrix: Θ(V²) space, O(1) edge lookup, O(V) to scan neighbours.
- Adjacency lists: Θ(V + E) space and O(deg(u)) to scan neighbours, which makes traversals O(V + E). The default for sparse graphs and for this course.
- Fix the neighbour order (sorted lists) when you need reproducible traces.