M23 · Graph Fundamentals

Graph Representations: Edge List, Adjacency Matrix and Adjacency List

A graph is just a set of nodes and the pairs that are connected, but how you store those pairs decides what is cheap. An edge list is compact but slow to query, a matrix answers “is there an edge?” instantly but costs V² memory, and adjacency lists make “visit every neighbour” proportional to the actual number of edges. Most algorithms in this course use lists.

~30 minIntermediateC# · Python · Java · C++
Curriculum: M23 Graph Fundamentals · 1 of 1 lessons available

You will be able to

  • Use the core vocabulary: directed and undirected, weighted, degree and in-degree, path, cycle, connected component, simple graph.
  • Convert a graph between an edge list, an adjacency matrix and adjacency lists by hand.
  • Compare the space and the cost of edge lookup, neighbour iteration, adding and removing an edge for each representation.
  • Classify a graph as sparse or dense from V and E, and choose a representation for a given workload.
  • Build adjacency lists in C#, Python, Java and C++ and explain why the lab sorts them.

Helpful before this lesson

  • M10 Hash Tables and Sets — Hashing, collisions and load factor: why lookups are expected O(1) and when they are not.
  • M07 Linked Lists — Nodes and pointers: what O(1) insertion really requires, and the classic pointer techniques.

Guidance only. Those modules are planned; the essentials are recapped here.

Visual walkthrough

The interactive visualizer needs JavaScript. The explanation and all four implementations below work without it.

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 edges u → v have 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.

Full implementation

BFS and DFS in four languages, each checked against one shared fixture of exact visit, distance, discovery and finish orders (directed and undirected, cycles, unreachable nodes, a grid, a single node) and 500 random graphs compared with Bellman-Ford distances and an explicit-stack DFS.

namespace Bekadan.Dsa.Examples.Graphs;
 
/// <summary>
/// Breadth-first and depth-first search on adjacency lists. Nodes are 0..n-1 and
/// every list is sorted ascending, so neighbours are always taken in increasing
/// order. Both run in O(V + E) time and O(V) extra space.
/// </summary>
public static class GraphTraversal
{
    /// <summary>Adjacency lists, neighbours ascending; an undirected edge goes into both lists.</summary>
    public static List<int>[] Adjacency(int nodeCount, IEnumerable<(int From, int To)> edges, bool directed)
    {
        var adj = new List<int>[nodeCount];
        for (int i = 0; i < nodeCount; i++)
            adj[i] = [];
        foreach (var (u, v) in edges)
        {
            adj[u].Add(v);
            if (!directed)
                adj[v].Add(u);
        }
        foreach (var list in adj)
            list.Sort();
        return adj;
    }
 
    /// <summary>Visit order and distance in edges from start (-1 = unreachable).</summary>
    public static (List<int> Order, int[] Distance) Bfs(List<int>[] adj, int start)
    {
        var order = new List<int>();
        var dist = new int[adj.Length];
        Array.Fill(dist, -1);
        dist[start] = 0;
        var queue = new Queue<int>();
        queue.Enqueue(start);
        while (queue.Count > 0)
        {
            int u = queue.Dequeue();
            order.Add(u);
            foreach (int v in adj[u])
            {
                if (dist[v] != -1)
                    continue; // already discovered
                dist[v] = dist[u] + 1;
                queue.Enqueue(v);
            }
        }
        return (order, dist);
    }
 
    /// <summary>Discovery (preorder) and finish (postorder) order of a recursive DFS from start.</summary>
    public static (List<int> Discovery, List<int> Finish) Dfs(List<int>[] adj, int start)
    {
        var visited = new bool[adj.Length];
        var discovery = new List<int>();
        var finish = new List<int>();
        Visit(adj, start, visited, discovery, finish);
        return (discovery, finish);
    }
 
    private static void Visit(List<int>[] adj, int u, bool[] visited, List<int> discovery, List<int> finish)
    {
        visited[u] = true;
        discovery.Add(u);
        foreach (int v in adj[u])
        {
            if (visited[v])
                continue;
            Visit(adj, v, visited, discovery, finish);
        }
        finish.Add(u);
    }
}

Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Graphs/GraphTraversal.cs

"""Breadth-first and depth-first search on adjacency lists.
 
Nodes are 0..n-1 and every list is sorted ascending, so neighbours are always
taken in increasing order. Both run in O(V + E) time and O(V) extra space.
"""
 
from __future__ import annotations
 
from collections import deque
from collections.abc import Iterable
 
 
def adjacency(node_count: int, edges: Iterable[tuple[int, int]], directed: bool) -> list[list[int]]:
    """Adjacency lists, neighbours ascending; an undirected edge goes into both lists."""
    adj: list[list[int]] = [[] for _ in range(node_count)]
    for u, v in edges:
        adj[u].append(v)
        if not directed:
            adj[v].append(u)
    for neighbours in adj:
        neighbours.sort()
    return adj
 
 
def bfs(adj: list[list[int]], start: int) -> tuple[list[int], list[int]]:
    """Visit order and distance in edges from start (-1 = unreachable)."""
    order: list[int] = []
    dist = [-1] * len(adj)
    dist[start] = 0
    queue = deque([start])
    while queue:
        u = queue.popleft()
        order.append(u)
        for v in adj[u]:
            if dist[v] != -1:
                continue  # already discovered
            dist[v] = dist[u] + 1
            queue.append(v)
    return order, dist
 
 
def dfs(adj: list[list[int]], start: int) -> tuple[list[int], list[int]]:
    """Discovery (preorder) and finish (postorder) order of a recursive DFS from start."""
    visited = [False] * len(adj)
    discovery: list[int] = []
    finish: list[int] = []
 
    def visit(u: int) -> None:
        visited[u] = True
        discovery.append(u)
        for v in adj[u]:
            if visited[v]:
                continue
            visit(v)
        finish.append(u)
 
    visit(start)
    return discovery, finish

Tested on CPython 3.14.0 · examples/python/dsa_examples/graph_traversal.py

package dev.bekadan.dsa.graphs;
 
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Queue;
 
/**
 * Breadth-first and depth-first search on adjacency lists. Nodes are 0..n-1 and
 * every list is sorted ascending, so neighbours are always taken in increasing
 * order. Both run in O(V + E) time and O(V) extra space.
 */
public final class GraphTraversal {
    private GraphTraversal() {
    }
 
    /** Visit order and distance in edges from the start (-1 = unreachable). */
    public record BfsResult(List<Integer> order, int[] distance) {
    }
 
    /** Discovery (preorder) and finish (postorder) order. */
    public record DfsResult(List<Integer> discovery, List<Integer> finish) {
    }
 
    /** Adjacency lists, neighbours ascending; an undirected edge goes into both lists. Each edge is {u, v}. */
    public static List<List<Integer>> adjacency(int nodeCount, int[][] edges, boolean directed) {
        List<List<Integer>> adj = new ArrayList<>(nodeCount);
        for (int i = 0; i < nodeCount; i++) {
            adj.add(new ArrayList<>());
        }
        for (int[] e : edges) {
            adj.get(e[0]).add(e[1]);
            if (!directed) {
                adj.get(e[1]).add(e[0]);
            }
        }
        for (List<Integer> list : adj) {
            Collections.sort(list);
        }
        return adj;
    }
 
    public static BfsResult bfs(List<List<Integer>> adj, int start) {
        List<Integer> order = new ArrayList<>();
        int[] dist = new int[adj.size()];
        Arrays.fill(dist, -1);
        dist[start] = 0;
        Queue<Integer> queue = new ArrayDeque<>();
        queue.add(start);
        while (!queue.isEmpty()) {
            int u = queue.remove();
            order.add(u);
            for (int v : adj.get(u)) {
                if (dist[v] != -1) {
                    continue; // already discovered
                }
                dist[v] = dist[u] + 1;
                queue.add(v);
            }
        }
        return new BfsResult(order, dist);
    }
 
    /** Recursive DFS from start. */
    public static DfsResult dfs(List<List<Integer>> adj, int start) {
        boolean[] visited = new boolean[adj.size()];
        List<Integer> discovery = new ArrayList<>();
        List<Integer> finish = new ArrayList<>();
        visit(adj, start, visited, discovery, finish);
        return new DfsResult(discovery, finish);
    }
 
    private static void visit(List<List<Integer>> adj, int u, boolean[] visited, List<Integer> discovery, List<Integer> finish) {
        visited[u] = true;
        discovery.add(u);
        for (int v : adj.get(u)) {
            if (visited[v]) {
                continue;
            }
            visit(adj, v, visited, discovery, finish);
        }
        finish.add(u);
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/graphs/GraphTraversal.java

#pragma once
 
#include <algorithm>
#include <cstddef>
#include <queue>
#include <utility>
#include <vector>
 
// Breadth-first and depth-first search on adjacency lists. Nodes are 0..n-1 and
// every list is sorted ascending, so neighbours are always taken in increasing
// order. Both run in O(V + E) time and O(V) extra space.
namespace bekadan::dsa::traversal {
 
using Adjacency = std::vector<std::vector<int>>;
 
// Adjacency lists, neighbours ascending; an undirected edge goes into both lists.
inline Adjacency adjacency(int node_count, const std::vector<std::pair<int, int>>& edges, bool directed) {
    Adjacency adj(node_count);
    for (const auto& [u, v] : edges) {
        adj[u].push_back(v);
        if (!directed) adj[v].push_back(u);
    }
    for (auto& list : adj) std::ranges::sort(list);
    return adj;
}
 
struct BfsResult {
    std::vector<int> order;
    std::vector<int> distance;  // -1 = unreachable
};
 
inline BfsResult bfs(const Adjacency& adj, int start) {
    std::vector<int> order;
    std::vector<int> dist(adj.size(), -1);
    dist[start] = 0;
    std::queue<int> queue;
    queue.push(start);
    while (!queue.empty()) {
        const int u = queue.front();
        queue.pop();
        order.push_back(u);
        for (const int v : adj[u]) {
            if (dist[v] != -1)
                continue;  // already discovered
            dist[v] = dist[u] + 1;
            queue.push(v);
        }
    }
    return {std::move(order), std::move(dist)};
}
 
struct DfsResult {
    std::vector<int> discovery;  // preorder
    std::vector<int> finish;     // postorder
    bool operator==(const DfsResult&) const = default;
};
 
namespace detail {
 
inline void visit(const Adjacency& adj, int u, std::vector<bool>& visited, DfsResult& out) {
    visited[u] = true;
    out.discovery.push_back(u);
    for (const int v : adj[u]) {
        if (visited[v])
            continue;
        visit(adj, v, visited, out);
    }
    out.finish.push_back(u);
}
 
}  // namespace detail
 
// Recursive DFS from start.
inline DfsResult dfs(const Adjacency& adj, int start) {
    std::vector<bool> visited(adj.size(), false);
    DfsResult out;
    detail::visit(adj, start, visited, out);
    return out;
}
 
}  // namespace bekadan::dsa::traversal

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/graph_traversal.hpp

References