data structuressets + graphs

graphs as data

one graph stored two ways, adjacency lists or a matrix, and when each one wins.

report a mistake
.md

a graph is vertices and the edges between them. adjacency lists keep each vertex's neighbors in a list of its own. an adjacency matrix keeps an n by n grid, with a 1 where two vertices are joined.

has edge
O(1) one cell of the matrix. the lists scan a row
neighbors
O(deg u) u's row of the lists. the matrix reads n cells
add, remove
O(1) two cells of the matrix. the lists scan a row first
lists hold
n + 2m a row per vertex, an entry per end of an edge
matrix holds
n² however few edges there are
reach for it
  • maps and road networks
  • who follows whom
  • tasks and what each one needs first
  • links between pages
  • the input to bfs, dfs, dijkstra and every other graph algorithm
on this page
  1. the idea
  2. the easy part
  3. the operations
  4. try it
  5. pseudocode
  6. sparse or dense, up close
  7. complexity
  8. implementations
  9. pitfalls
  10. variants
  11. practice
  12. how real libraries do it
  13. sources

a graph is a set of vertices and the edges between them. the vertices are the easy part: number them 0 to n - 1. the edges are the data, and how they’re stored decides what’s cheap. adjacency lists keep each vertex’s neighbors in a list of its own. an adjacency matrix keeps a grid with a cell for every pair. one asks for memory that follows the edges, the other answers is there an edge in one step.

the idea

a graph: 6 vertices, numbered 0 to 5, and 7 edges. an edge joins two vertices, either way round. here they go in one at a time.

an animation in five steps. first a graph of 6 vertices, 0 to 5, on a circle, gets its 7 edges one at a time. then its adjacency lists appear, a row per vertex, and row 1, holding 0, 2 and 3, turns cyan with vertex 1's three edges. then its adjacency matrix appears, 6 by 6, and the edge between 1 and 3 turns white along with the two cells it sets, row 1, column 3 and row 3, column 1. then the edge 1, 4 goes in: it shows dashed, 4 appears in white at the end of row 1 and 1 at the end of row 4, two cells of the matrix change from 0 to 1, and the edge turns solid. last, has edge 2, 5: the lists scan row 2 one entry at a time, 0, 1 and 4, and find no 5. the matrix reads one cell, row 2, column 5, which is 0.

the easy part

on this page the edges have no direction: an edge between 1 and 3 is also an edge between 3 and 1. an edge joins two different vertices, and two vertices have at most one edge between them. the questions to answer fast: is there an edge between u and v, and which vertices are joined to u?

the operations

01234567

lists

matrix

tap a vertex to fill in u, then v.

tap two vertices, or type them, then add or remove the edge between them, or ask if it's there. neighbors of u reads u's row in both.

steps, lists
0
steps, matrix
0
lists hold
8 + 2 × 7 = 22 entries
matrix holds
8 × 8 = 64 cells
pseudocode
has_edge(list, u, v):  for w in list[u]:  # one step per neighbor of u    if w == v: return true  return false has_edge(matrix, u, v):  return matrix[u][v]  # one cell add_edge(g, u, v):  if u == v or has_edge(g, u, v): return false  list[u].append(v); list[v].append(u)  matrix[u][v] = matrix[v][u] = true  return true remove_edge(g, u, v):  if not has_edge(g, u, v): return false  for a, b in (u, v), (v, u):    i = list[a].index(b)    list[a][i] = list[a][-1]  # the last neighbor fills the hole    list[a].pop()  matrix[u][v] = matrix[v][u] = false  return true neighbors(list, u):  return list[u]  # degree(u) entries neighbors(matrix, u):  return [v for v in 0 .. n - 1 if matrix[u][v]]  # n cells

an interactive graph of 8 vertices on a circle, with its adjacency lists and its adjacency matrix beside it. it starts with the 7 edges of the graph above, and vertices 6 and 7 have none. tap two vertices, or type them as u and v, then add or remove the edge between them, ask whether it's there, or list u's neighbors. random edge adds one. u is cyan and v amber in all three pictures, the list entry or matrix cell being read or written is white, and an edge going in or out is dashed. the matching pseudocode line is highlighted, with counts of the steps each picture took, and of what each holds: 8 + 2m entries for the lists, 64 cells for the matrix.

add the edge 1, 4, then ask has edge 2, 5: the lists scan all of row 2, and the matrix reads one cell. remove 0, 1 and watch row 1: its last entry moves into the hole 0 leaves. then tap 6 and press neighbors of u: an empty row of the lists is nothing to read, but the matrix still reads all 8 cells of row 6.

try it

has_edge(2, 1) on the lists: how many entries does the scan look at?

lists

pick one.

0 / 0 right

a practice exercise on small graphs. some questions show the adjacency lists and ask how many entries a has edge scan looks at, or what a row looks like after a remove. others show the matrix and ask for a vertex's degree, or show the drawing and ask how many 1s its matrix holds.

pseudocode

pseudocode
has_edge(list, u, v):
  for w in list[u]:  # one step per neighbor of u
    if w == v: return true
  return false

has_edge(matrix, u, v):
  return matrix[u][v]  # one cell

add_edge(g, u, v):
  if u == v or has_edge(g, u, v): return false
  list[u].append(v); list[v].append(u)
  matrix[u][v] = matrix[v][u] = true
  return true

remove_edge(g, u, v):
  if not has_edge(g, u, v): return false
  for a, b in (u, v), (v, u):
    i = list[a].index(b)
    list[a][i] = list[a][-1]  # the last neighbor fills the hole
    list[a].pop()
  matrix[u][v] = matrix[v][u] = false
  return true

neighbors(list, u):
  return list[u]  # degree(u) entries

neighbors(matrix, u):
  return [v for v in 0 .. n - 1 if matrix[u][v]]  # n cells

a remove from a list doesn’t shift the rest of the row down. it moves the last neighbor into the hole, one step after the scan, and the row’s order changes. the order of a row was never sorted anyway: it’s the order the edges went in. every tab removes this way, so the rows match across languages.

sparse or dense, up close

the matrix answers has edge in one step, and the lists in up to deg u. what the matrix costs is room.

bars comparing list entries with matrix cells for 10, 1,000 or 1,000,000 vertices, picked with buttons, and two kinds of graph: every vertex with 4 neighbors, and every pair joined. with 4 neighbors each, the lists hold 5 entries per vertex: 50, 5,000 or 5,000,000, while the matrix has 100, 1,000,000 or 1,000,000,000,000 cells, of which 40%, 0.4% or 0.0004% are set. with every pair joined, the lists hold n² entries, as many as the matrix has cells: 100, 1,000,000 or 1,000,000,000,000, and 90%, 99.9% or 99.9999% of the cells are set.

complexity

operationlistsmatrix
has edgeO(deg u)O(1)
add edgeO(deg u)O(1)
remove edgeO(deg u + deg v)O(1)
neighborsO(deg u)O(n)
degreeO(1)O(n)
memoryO(n + m)O(n²)

deg u is at most n - 1, and in a sparse graph a small number however big n gets. add edge on the lists is an append, amortized O(1) as on the dynamic array page, after a scan of u’s row to turn away a repeat. remove scans both rows to find the two entries. the matrix pays for its O(1) with its O(n) rows: neighbors and degree read all of one.

implementations

each tab is the real file from the repo, checked by its tests (go test, cargo test, vitest, make test, swift test, python -m unittest), including 2000 seeded adds, removes and lookups against a set of pairs, on both. every tab has both representations, and removes from a list by moving the last neighbor into the hole, so the rows come out in the same order in every language. the tests also check that the matrix lists neighbors smallest first, and that the lists hold a million vertices, where a matrix would need 1,000,000,000,000 cells. typescript and python turn away a vertex out of range with an error. go, rust and swift stop where a bad vertex is used as an index, and their matrices check the row and the column apart, so a v past the end can’t read a cell in the next row. c’s header asks for vertices below n.

go/algos/graph/graph.go
// Package graph is a reference for graphs as data: one undirected graph on vertices 0 to n - 1, stored two
// ways. an adjacency list keeps each vertex's neighbors in an array of their own: n + 2m entries for m
// edges, and has edge scans one vertex's list. an adjacency matrix keeps an n by n grid of yes and no: n²
// cells, and has edge reads one. both turn away an edge from a vertex to itself, and an edge that's
// already there.
package graph

import "slices"

// Graph is one undirected graph on vertices 0 to n - 1, however it's stored. Nothing checks a vertex:
// one outside 0 to n - 1 is a bug, and indexing with it panics.
type Graph interface {
	// Vertices returns how many vertices there are: 0 to n - 1.
	Vertices() int
	// Edges returns how many edges there are.
	Edges() int
	// AddEdge joins u and v. It returns false for u == v, or an edge that's already there.
	AddEdge(u, v int) bool
	// RemoveEdge takes the edge between u and v out. It returns false if there isn't one.
	RemoveEdge(u, v int) bool
	// HasEdge reports whether u and v are joined.
	HasEdge(u, v int) bool
	// Neighbors returns the vertices joined to u, in a new slice.
	Neighbors(u int) []int
	// Degree returns how many edges touch u.
	Degree(u int) int
}

// List keeps a slice of neighbors per vertex, in the order their edges went in.
type List struct {
	adj   [][]int // adj[u] holds u's neighbors
	edges int
}

// NewList returns a graph on n vertices with no edges, stored as an adjacency list.
func NewList(n int) *List {
	return &List{adj: make([][]int, n)} // n lists, each nil: a nil slice is empty, and append grows it
}

// Vertices returns how many vertices there are.
func (g *List) Vertices() int {
	return len(g.adj)
}

// Edges returns how many edges there are.
func (g *List) Edges() int {
	return g.edges
}

// HasEdge scans u's list for v: one step per neighbor.
func (g *List) HasEdge(u, v int) bool {
	return slices.Contains(g.adj[u], v)
}

// AddEdge puts each end on the other's list. It returns false for u == v, or an edge that's already there.
func (g *List) AddEdge(u, v int) bool {
	if u == v || g.HasEdge(u, v) {
		return false
	}
	// v's list first: HasEdge only indexed u, so a v out of range panics here, before anything changes
	g.adj[v] = append(g.adj[v], u)
	g.adj[u] = append(g.adj[u], v)
	g.edges++
	return true
}

// RemoveEdge takes each end off the other's list. It returns false if there's no edge between u and v.
func (g *List) RemoveEdge(u, v int) bool {
	if !g.HasEdge(u, v) {
		return false
	}
	g.drop(u, v)
	g.drop(v, u)
	g.edges--
	return true
}

// drop takes v off u's list: the last neighbor moves into its place, so nothing shifts.
func (g *List) drop(u, v int) {
	list := g.adj[u]
	last := len(list) - 1
	list[slices.Index(list, v)] = list[last]
	g.adj[u] = list[:last]
}

// Neighbors returns a copy of u's list.
func (g *List) Neighbors(u int) []int {
	return slices.Clone(g.adj[u])
}

// Degree returns how many edges touch u: the length of its list.
func (g *List) Degree(u int) int {
	return len(g.adj[u])
}

// Matrix keeps an n by n grid in one flat slice, row after row: cell u * n + v is true when u and v are
// joined, and so is cell v * n + u.
type Matrix struct {
	n     int
	cells []bool
	edges int
}

// NewMatrix returns a graph on n vertices with no edges, stored as an adjacency matrix: n * n cells.
func NewMatrix(n int) *Matrix {
	return &Matrix{n: n, cells: make([]bool, n*n)}
}

// Vertices returns how many vertices there are.
func (g *Matrix) Vertices() int {
	return g.n
}

// Edges returns how many edges there are.
func (g *Matrix) Edges() int {
	return g.edges
}

// row returns u's row: cells u * n to u * n + n - 1. Taking the row before the cell means a vertex out
// of range panics, where u * n + v on its own could land on a cell in another row.
func (g *Matrix) row(u int) []bool {
	return g.cells[u*g.n : (u+1)*g.n]
}

// HasEdge reads one cell, however many neighbors u has.
func (g *Matrix) HasEdge(u, v int) bool {
	return g.row(u)[v]
}

// AddEdge sets cell u, v and cell v, u. It returns false for u == v, or an edge that's already there.
func (g *Matrix) AddEdge(u, v int) bool {
	if u == v || g.HasEdge(u, v) {
		return false
	}
	g.row(u)[v] = true
	g.row(v)[u] = true
	g.edges++
	return true
}

// RemoveEdge clears cell u, v and cell v, u. It returns false if there's no edge between u and v.
func (g *Matrix) RemoveEdge(u, v int) bool {
	if !g.HasEdge(u, v) {
		return false
	}
	g.row(u)[v] = false
	g.row(v)[u] = false
	g.edges--
	return true
}

// Neighbors reads u's whole row: n cells, however few are set. The neighbors come out ascending.
func (g *Matrix) Neighbors(u int) []int {
	var out []int
	for v, joined := range g.row(u) {
		if joined {
			out = append(out, v)
		}
	}
	return out
}

// Degree returns how many edges touch u. It reads the whole row too.
func (g *Matrix) Degree(u int) int {
	return len(g.Neighbors(u))
}
rust/algos/src/graph.rs
//! graphs as data: one undirected graph on vertices 0 to n - 1, stored two ways. an adjacency list keeps each vertex's neighbors in an array of their own: n + 2m entries for m edges, and has edge scans one vertex's list. an adjacency matrix keeps an n by n grid of yes and no: n² cells, and has edge reads one. both turn away an edge from a vertex to itself, and an edge that's already there.

/// One undirected graph on vertices 0 to n - 1: an edge joins two different vertices, and two
/// vertices have at most one edge between them. A vertex past n - 1 panics where it's used as an
/// index, as any index out of range does: there's no check of its own.
pub trait Graph {
    /// How many vertices: 0 to n - 1.
    fn vertices(&self) -> usize;

    /// How many edges.
    fn edges(&self) -> usize;

    /// Joins `u` and `v`. False for `u == v`, or an edge that's already there.
    fn add_edge(&mut self, u: usize, v: usize) -> bool;

    /// Takes the edge between `u` and `v` out. False if there isn't one.
    fn remove_edge(&mut self, u: usize, v: usize) -> bool;

    /// Whether `u` and `v` are joined.
    fn has_edge(&self, u: usize, v: usize) -> bool;

    /// The vertices joined to `u`, in a new `Vec`.
    fn neighbors(&self, u: usize) -> Vec<usize>;

    /// How many edges touch `u`.
    fn degree(&self, u: usize) -> usize;
}

/// A list of neighbors per vertex, in the order their edges went in. An edge is on two lists,
/// one at each end.
pub struct AdjList {
    adj: Vec<Vec<usize>>,
    edges: usize,
}

impl AdjList {
    /// Makes `n` vertices and no edges: an empty list for each.
    pub fn new(n: usize) -> Self {
        Self {
            adj: vec![Vec::new(); n],
            edges: 0,
        }
    }
}

impl Graph for AdjList {
    fn vertices(&self) -> usize {
        self.adj.len()
    }

    fn edges(&self) -> usize {
        self.edges
    }

    /// Scans `u`'s list for `v`: one step per neighbor.
    fn has_edge(&self, u: usize, v: usize) -> bool {
        self.adj[u].contains(&v)
    }

    /// Each end goes on the other's list.
    fn add_edge(&mut self, u: usize, v: usize) -> bool {
        if u == v || self.has_edge(u, v) {
            return false;
        }
        // v's list first: has_edge only indexed u, so a v past n - 1 panics here, before
        // anything has changed
        self.adj[v].push(u);
        self.adj[u].push(v);
        self.edges += 1;
        true
    }

    /// Each end comes off the other's list: the last neighbor moves into its place, so nothing
    /// shifts.
    fn remove_edge(&mut self, u: usize, v: usize) -> bool {
        if !self.has_edge(u, v) {
            return false;
        }
        for (a, b) in [(u, v), (v, u)] {
            let list = &mut self.adj[a];
            let i = list
                .iter()
                .position(|&w| w == b)
                .expect("each end is on the other's list");
            list.swap_remove(i);
        }
        self.edges -= 1;
        true
    }

    fn neighbors(&self, u: usize) -> Vec<usize> {
        self.adj[u].clone()
    }

    fn degree(&self, u: usize) -> usize {
        self.adj[u].len()
    }
}

/// An n by n grid of bools in one `Vec`, a row per vertex: cell `u * n + v` is true when `u` and
/// `v` are joined, and so is cell `v * n + u`.
pub struct AdjMatrix {
    n: usize,
    cells: Vec<bool>,
    edges: usize,
}

impl AdjMatrix {
    /// Makes `n` vertices and no edges: n * n cells, all false.
    pub fn new(n: usize) -> Self {
        Self {
            n,
            cells: vec![false; n * n],
            edges: 0,
        }
    }

    /// Row `u`: the n cells from `u * n` on, one per vertex. Indexing the row with `v`, not the
    /// whole grid with `u * n + v`, makes a `v` past n - 1 panic instead of reading the next row.
    fn row(&self, u: usize) -> &[bool] {
        &self.cells[u * self.n..(u + 1) * self.n]
    }

    /// Row `u`, to write to.
    fn row_mut(&mut self, u: usize) -> &mut [bool] {
        &mut self.cells[u * self.n..(u + 1) * self.n]
    }
}

impl Graph for AdjMatrix {
    fn vertices(&self) -> usize {
        self.n
    }

    fn edges(&self) -> usize {
        self.edges
    }

    /// One cell, however many neighbors `u` has.
    fn has_edge(&self, u: usize, v: usize) -> bool {
        self.row(u)[v]
    }

    fn add_edge(&mut self, u: usize, v: usize) -> bool {
        if u == v || self.has_edge(u, v) {
            return false;
        }
        self.row_mut(u)[v] = true;
        self.row_mut(v)[u] = true;
        self.edges += 1;
        true
    }

    fn remove_edge(&mut self, u: usize, v: usize) -> bool {
        if !self.has_edge(u, v) {
            return false;
        }
        self.row_mut(u)[v] = false;
        self.row_mut(v)[u] = false;
        self.edges -= 1;
        true
    }

    /// Reads `u`'s whole row in order: n cells, however few are set. So the neighbors come out
    /// smallest first.
    fn neighbors(&self, u: usize) -> Vec<usize> {
        let row = self.row(u);
        (0..self.n).filter(|&v| row[v]).collect()
    }

    /// Counts the true cells in `u`'s row: n cells, like neighbors.
    fn degree(&self, u: usize) -> usize {
        self.row(u).iter().filter(|&&joined| joined).count()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::BTreeSet;

    /// Makes an empty graph with n vertices.
    type Make = fn(usize) -> Box<dyn Graph>;

    /// Both ways of storing a graph, by name. The first six tests run on each, and want the same
    /// answers from both.
    const BOTH: [(&str, Make); 2] = [
        ("adjacency list", |n| Box::new(AdjList::new(n))),
        ("adjacency matrix", |n| Box::new(AdjMatrix::new(n))),
    ];

    fn from(
        make: Make,
        n: usize,
        edges: impl IntoIterator<Item = (usize, usize)>,
    ) -> Box<dyn Graph> {
        let mut g = make(n);
        for (u, v) in edges {
            g.add_edge(u, v);
        }
        g
    }

    /// `xs` smallest first, so the list's order and the matrix's compare the same.
    fn sorted(mut xs: Vec<usize>) -> Vec<usize> {
        xs.sort();
        xs
    }

    // the page's graph: 6 vertices, 7 edges
    const EDGES: [(usize, usize); 7] = [(0, 1), (0, 2), (1, 2), (1, 3), (2, 4), (3, 5), (4, 5)];

    #[test]
    fn starts_with_n_vertices_and_no_edges() {
        for (name, make) in BOTH {
            let g = make(6);
            assert_eq!(
                (
                    g.vertices(),
                    g.edges(),
                    g.has_edge(0, 1),
                    g.neighbors(0),
                    g.degree(5)
                ),
                (6, 0, false, vec![], 0),
                "{name}"
            );
        }
    }

    #[test]
    fn an_edge_joins_both_ends() {
        for (name, make) in BOTH {
            let mut g = make(6);
            assert_eq!(
                (
                    g.add_edge(1, 4),
                    g.edges(),
                    g.has_edge(1, 4),
                    g.has_edge(4, 1)
                ),
                (true, 1, true, true),
                "{name}"
            );
            assert_eq!(
                (g.neighbors(1), g.neighbors(4), g.degree(1), g.degree(0)),
                (vec![4], vec![1], 1, 0),
                "{name}"
            );
        }
    }

    #[test]
    fn an_edge_to_itself_or_one_that_is_already_there_is_turned_away() {
        for (name, make) in BOTH {
            let mut g = from(make, 6, EDGES);
            assert_eq!(
                (
                    g.add_edge(3, 3),
                    g.add_edge(0, 1),
                    g.add_edge(1, 0),
                    g.edges()
                ),
                (false, false, false, 7),
                "{name}"
            );
        }
    }

    #[test]
    fn the_pages_graph_6_vertices_7_edges_and_every_degree() {
        for (name, make) in BOTH {
            let g = from(make, 6, EDGES);
            assert_eq!(
                (g.edges(), [0, 1, 2, 3, 4, 5].map(|u| g.degree(u))),
                (7, [2, 3, 3, 2, 2, 2]),
                "{name}"
            );
            assert_eq!(
                (sorted(g.neighbors(2)), g.has_edge(2, 5), g.has_edge(5, 4)),
                (vec![0, 1, 4], false, true),
                "{name}"
            );
        }
    }

    #[test]
    fn remove_takes_the_edge_off_both_ends_and_a_missing_edge_says_so() {
        for (name, make) in BOTH {
            let mut g = from(make, 6, EDGES);
            assert_eq!(
                (
                    g.remove_edge(2, 1),
                    g.edges(),
                    g.has_edge(1, 2),
                    g.has_edge(2, 1)
                ),
                (true, 6, false, false),
                "{name}"
            );
            assert_eq!(
                (sorted(g.neighbors(1)), sorted(g.neighbors(2))),
                (vec![0, 3], vec![0, 4]),
                "{name}"
            );
            assert_eq!(
                (g.remove_edge(1, 2), g.remove_edge(0, 5), g.edges()),
                (false, false, 6),
                "{name}"
            );
        }
    }

    #[test]
    fn agrees_with_a_set_of_pairs_over_2000_seeded_operations() {
        for (name, make) in BOTH {
            // xorshift32 seeded with 42, like the other tests here
            let mut state: u32 = 42;
            let mut next = || {
                state ^= state << 13;
                state ^= state >> 17;
                state ^= state << 5;
                state as usize
            };
            let n = 12;
            let mut g = make(n);
            // the model: each edge once, as a pair with the smaller end first
            let key = |u: usize, v: usize| (u.min(v), u.max(v));
            let mut model = BTreeSet::new();
            for _ in 0..2000 {
                let u = next() % n;
                let v = next() % n;
                match next() % 4 {
                    0 => {
                        let fresh = u != v && !model.contains(&key(u, v));
                        assert_eq!(g.add_edge(u, v), fresh, "{name}");
                        if fresh {
                            model.insert(key(u, v));
                        }
                    }
                    1 => assert_eq!(g.remove_edge(u, v), model.remove(&key(u, v)), "{name}"),
                    2 => assert_eq!(g.has_edge(u, v), model.contains(&key(u, v)), "{name}"),
                    _ => {
                        let want: Vec<usize> =
                            (0..n).filter(|&w| model.contains(&key(u, w))).collect();
                        assert_eq!(
                            (sorted(g.neighbors(u)), g.degree(u)),
                            (want.clone(), want.len()),
                            "{name}"
                        );
                    }
                }
                assert_eq!(g.edges(), model.len(), "{name}");
            }
        }
    }

    // the two side by side

    #[test]
    fn the_list_keeps_neighbors_in_the_order_they_went_in_and_a_remove_moves_the_last_one_into_the_hole()
     {
        let mut list = AdjList::new(5);
        let mut matrix = AdjMatrix::new(5);
        for v in [3, 1, 4, 2] {
            list.add_edge(0, v);
            matrix.add_edge(0, v);
        }
        assert_eq!(
            (list.neighbors(0), matrix.neighbors(0)),
            (vec![3, 1, 4, 2], vec![1, 2, 3, 4])
        );
        list.remove_edge(0, 1);
        matrix.remove_edge(0, 1);
        assert_eq!(
            (list.neighbors(0), matrix.neighbors(0)),
            (vec![3, 2, 4], vec![2, 3, 4])
        );
    }

    #[test]
    fn a_million_vertices_and_a_few_edges_the_list_is_cheap_where_a_matrix_would_need_10_to_the_12_cells()
     {
        let mut g = AdjList::new(1_000_000);
        for v in 1..1000 {
            g.add_edge(0, v);
        }
        assert_eq!(
            (g.vertices(), g.edges(), g.degree(0), g.has_edge(999, 0)),
            (1_000_000, 999, 999, true)
        );
    }
}
site/src/visuals/graph/graph.ts
/**
 * Graphs as data: one undirected graph on vertices 0 to n - 1, stored two ways. An adjacency list keeps each
 * vertex's neighbors in an array of their own: n + 2m entries for m edges, and has edge scans one vertex's list. An
 * adjacency matrix keeps an n by n grid of yes and no: n² cells, and has edge reads one. Both turn away an edge
 * from a vertex to itself, and an edge that's already there.
 */
export interface Graph {
  /** How many vertices: 0 to n - 1. */
  readonly vertices: number;
  /** How many edges. */
  readonly edges: number;
  /** Join u and v. False for u = v, or an edge that's already there. */
  addEdge(u: number, v: number): boolean;
  /** Take the edge between u and v out. False if there isn't one. */
  removeEdge(u: number, v: number): boolean;
  hasEdge(u: number, v: number): boolean;
  /** The vertices joined to u. */
  neighbors(u: number): number[];
  /** How many edges touch u. */
  degree(u: number): number;
}

function check(n: number, ...vs: number[]) {
  for (const v of vs) if (!Number.isInteger(v) || v < 0 || v >= n) throw new RangeError(`no vertex ${v}`);
}

/** A list of neighbors per vertex, in the order their edges went in. */
export class AdjList implements Graph {
  #adj: number[][];
  #edges = 0;

  constructor(n: number) {
    this.#adj = Array.from({ length: n }, () => []);
  }

  get vertices(): number {
    return this.#adj.length;
  }

  get edges(): number {
    return this.#edges;
  }

  /** Scan u's list for v: one step per neighbor. */
  hasEdge(u: number, v: number): boolean {
    check(this.vertices, u, v);
    return this.#adj[u].includes(v);
  }

  /** Each end goes on the other's list. */
  addEdge(u: number, v: number): boolean {
    if (u === v || this.hasEdge(u, v)) return false;
    this.#adj[u].push(v);
    this.#adj[v].push(u);
    this.#edges += 1;
    return true;
  }

  /** Each end comes off the other's list: the last neighbor moves into its place, so nothing shifts. */
  removeEdge(u: number, v: number): boolean {
    if (!this.hasEdge(u, v)) return false;
    for (const [a, b] of [
      [u, v],
      [v, u],
    ]) {
      const list = this.#adj[a];
      list[list.indexOf(b)] = list[list.length - 1];
      list.pop();
    }
    this.#edges -= 1;
    return true;
  }

  neighbors(u: number): number[] {
    check(this.vertices, u);
    return [...this.#adj[u]];
  }

  degree(u: number): number {
    check(this.vertices, u);
    return this.#adj[u].length;
  }
}

/** An n by n grid: cell u, v is true when u and v are joined, and so is cell v, u. */
export class AdjMatrix implements Graph {
  #n: number;
  #cells: boolean[];
  #edges = 0;

  constructor(n: number) {
    this.#n = n;
    this.#cells = Array<boolean>(n * n).fill(false);
  }

  get vertices(): number {
    return this.#n;
  }

  get edges(): number {
    return this.#edges;
  }

  /** One cell, however many neighbors u has. */
  hasEdge(u: number, v: number): boolean {
    check(this.#n, u, v);
    return this.#cells[u * this.#n + v];
  }

  addEdge(u: number, v: number): boolean {
    if (u === v || this.hasEdge(u, v)) return false;
    this.#cells[u * this.#n + v] = true;
    this.#cells[v * this.#n + u] = true;
    this.#edges += 1;
    return true;
  }

  removeEdge(u: number, v: number): boolean {
    if (!this.hasEdge(u, v)) return false;
    this.#cells[u * this.#n + v] = false;
    this.#cells[v * this.#n + u] = false;
    this.#edges -= 1;
    return true;
  }

  /** Read u's whole row: n cells, however few are set. */
  neighbors(u: number): number[] {
    check(this.#n, u);
    const out: number[] = [];
    for (let v = 0; v < this.#n; v++) if (this.#cells[u * this.#n + v]) out.push(v);
    return out;
  }

  degree(u: number): number {
    return this.neighbors(u).length;
  }
}
c/algos/graph.c
/* graphs as data: one undirected graph on vertices 0 to n - 1, stored two ways. an adjacency list keeps each vertex's neighbors in an array of their own: n + 2m entries for m edges, and has edge scans one vertex's list. an adjacency matrix keeps an n by n grid of yes and no: n² cells, and has edge reads one. both turn away an edge from a vertex to itself, and an edge that's already there. */
#include "graph.h"

#include <stdlib.h>

/* n = 0 stops before the callocs: calloc(0, ...) can return NULL, which would look like a failure.
   n goes in last, once all three arrays are there: if one calloc fails, adjlist_free frees the
   others (free(NULL) does nothing) and has no lists to walk */
bool adjlist_init(AdjList *g, size_t n) {
    *g = (AdjList){0};
    if (n == 0) return true;
    /* calloc: every list starts NULL, with a length and room of 0 */
    g->adj = calloc(n, sizeof *g->adj);
    g->len = calloc(n, sizeof *g->len);
    g->cap = calloc(n, sizeof *g->cap);
    if (!g->adj || !g->len || !g->cap) {
        adjlist_free(g);
        return false;
    }
    g->n = n;
    return true;
}

void adjlist_free(AdjList *g) {
    for (size_t u = 0; u < g->n; u++) free(g->adj[u]);
    free(g->adj);
    free(g->len);
    free(g->cap);
    *g = (AdjList){0}; /* no vertices and no edges */
}

/* where b is on a's list, or len[a] if it isn't there */
static size_t find(const AdjList *g, size_t a, size_t b) {
    size_t i = 0;
    while (i < g->len[a] && g->adj[a][i] != b) i++;
    return i;
}

/* one step per neighbor of u: nothing says where on the list v would be */
bool adjlist_has_edge(const AdjList *g, size_t u, size_t v) {
    return find(g, u, v) < g->len[u];
}

/* room for one more neighbor on u's list: 4 slots at first, then twice as many each time it
   fills. a list starts NULL, and realloc(NULL, size) is malloc(size). if realloc fails, the old
   block is still there, so nothing is lost */
static bool make_room(AdjList *g, size_t u) {
    if (g->len[u] < g->cap[u]) return true;
    size_t cap = g->cap[u] ? 2 * g->cap[u] : 4;
    size_t *bigger = realloc(g->adj[u], cap * sizeof *bigger);
    if (!bigger) return false;
    g->adj[u] = bigger;
    g->cap[u] = cap;
    return true;
}

/* room on both lists first, then both ends go in, so a failed grow can't leave the edge on one
   list and not the other. if v's list can't grow after u's did, u's keeps its new room, which
   changes none of its neighbors */
bool adjlist_add_edge(AdjList *g, size_t u, size_t v, bool *added) {
    *added = false;
    if (u == v || adjlist_has_edge(g, u, v)) return true; /* turned away: nothing changes */
    if (!make_room(g, u) || !make_room(g, v)) return false;
    g->adj[u][g->len[u]++] = v;
    g->adj[v][g->len[v]++] = u;
    g->edges++;
    *added = true;
    return true;
}

/* takes b off a's list: a's last neighbor moves into b's place, so nothing shifts. if b is the
   last, it lands on itself, and the shorter length drops it. returns false if b isn't there */
static bool take(AdjList *g, size_t a, size_t b) {
    size_t i = find(g, a, b);
    if (i == g->len[a]) return false;
    g->adj[a][i] = g->adj[a][--g->len[a]];
    return true;
}

bool adjlist_remove_edge(AdjList *g, size_t u, size_t v) {
    if (!take(g, u, v)) return false; /* no such edge */
    take(g, v, u); /* every edge is on both its ends' lists */
    g->edges--;
    return true;
}

size_t adjlist_degree(const AdjList *g, size_t u) {
    return g->len[u];
}

/* n = 0 stops before the calloc, and n goes in last, as in adjlist_init. n rows of n cells:
   calloc multiplies the two itself, and returns NULL if the product doesn't fit in a size_t, where
   n * n written out would wrap around to a smaller number and get a block too small */
bool adjmatrix_init(AdjMatrix *g, size_t n) {
    *g = (AdjMatrix){0};
    if (n == 0) return true;
    g->cells = calloc(n, n * sizeof *g->cells); /* calloc: every cell false */
    if (!g->cells) return false;
    g->n = n;
    return true;
}

void adjmatrix_free(AdjMatrix *g) {
    free(g->cells);
    *g = (AdjMatrix){0}; /* no vertices and no edges */
}

/* one cell, however many neighbors u has */
bool adjmatrix_has_edge(const AdjMatrix *g, size_t u, size_t v) {
    return g->cells[u * g->n + v];
}

/* both cells, so the grid stays symmetric: either order finds the edge */
bool adjmatrix_add_edge(AdjMatrix *g, size_t u, size_t v) {
    if (u == v || adjmatrix_has_edge(g, u, v)) return false;
    g->cells[u * g->n + v] = true;
    g->cells[v * g->n + u] = true;
    g->edges++;
    return true;
}

bool adjmatrix_remove_edge(AdjMatrix *g, size_t u, size_t v) {
    if (!adjmatrix_has_edge(g, u, v)) return false;
    g->cells[u * g->n + v] = false;
    g->cells[v * g->n + u] = false;
    g->edges--;
    return true;
}

/* u's whole row: n cells, however few are set. it's read left to right, so the neighbors come out
   smallest first */
size_t adjmatrix_neighbors(const AdjMatrix *g, size_t u, size_t *out) {
    const bool *row = g->cells + u * g->n;
    size_t count = 0;
    for (size_t v = 0; v < g->n; v++) {
        if (row[v]) out[count++] = v;
    }
    return count;
}

/* the same walk along u's row, counting instead of writing */
size_t adjmatrix_degree(const AdjMatrix *g, size_t u) {
    const bool *row = g->cells + u * g->n;
    size_t count = 0;
    for (size_t v = 0; v < g->n; v++) count += row[v];
    return count;
}
swift/algos/Graph.swift
/// graphs as data: one undirected graph on vertices 0 to n - 1, stored two ways. an adjacency list keeps each vertex's neighbors in an array of their own: n + 2m entries for m edges, and has edge scans one vertex's list. an adjacency matrix keeps an n by n grid of yes and no: n² cells, and has edge reads one. both turn away an edge from a vertex to itself, and an edge that's already there.
/// two structs behind one protocol, since each is just arrays and counts: copying one copies the graph.
public protocol Graph {
    /// how many vertices: 0 to n - 1
    var vertices: Int { get }
    /// how many edges
    var edges: Int { get }
    /// joins u and v. false for u = v, or an edge that's already there
    @discardableResult
    mutating func addEdge(_ u: Int, _ v: Int) -> Bool
    /// takes the edge between u and v out. false if there isn't one
    @discardableResult
    mutating func removeEdge(_ u: Int, _ v: Int) -> Bool
    /// whether u and v are joined
    func hasEdge(_ u: Int, _ v: Int) -> Bool
    /// the vertices joined to u
    func neighbors(_ u: Int) -> [Int]
    /// how many edges touch u
    func degree(_ u: Int) -> Int
}

/// a list of neighbors per vertex, in the order their edges went in
public struct AdjList: Graph {
    // u's neighbors are adj[u]. an edge is in two lists, one for each end
    private var adj: [[Int]]
    public private(set) var edges = 0

    /// n vertices and no edges: an empty list for each
    public init(_ n: Int) {
        adj = Array(repeating: [], count: n)
    }

    public var vertices: Int { adj.count }

    /// scans u's list for v: one step per neighbor
    public func hasEdge(_ u: Int, _ v: Int) -> Bool {
        adj[u].contains(v)
    }

    /// each end goes on the other's list
    @discardableResult
    public mutating func addEdge(_ u: Int, _ v: Int) -> Bool {
        if u == v || hasEdge(u, v) { return false }
        adj[u].append(v)
        adj[v].append(u)
        edges += 1
        return true
    }

    /// each end comes off the other's list: the last neighbor moves into its place, so nothing shifts
    @discardableResult
    public mutating func removeEdge(_ u: Int, _ v: Int) -> Bool {
        guard hasEdge(u, v) else { return false }
        for (a, b) in [(u, v), (v, u)] {
            let i = adj[a].firstIndex(of: b)!
            adj[a][i] = adj[a].last!
            adj[a].removeLast()
        }
        edges -= 1
        return true
    }

    public func neighbors(_ u: Int) -> [Int] {
        adj[u]
    }

    public func degree(_ u: Int) -> Int {
        adj[u].count
    }
}

/// an n by n grid: cell u, v is true when u and v are joined, and so is cell v, u
public struct AdjMatrix: Graph {
    private let n: Int
    // the n rows one after another, so cell u, v is at u * n + v
    private var cells: [Bool]
    public private(set) var edges = 0

    /// n vertices and no edges: n * n cells, all false
    public init(_ n: Int) {
        self.n = n
        cells = Array(repeating: false, count: n * n)
    }

    public var vertices: Int { n }

    // where cell u, v sits. a v past n - 1 would land in the next row instead of trapping, so both are checked
    private func cell(_ u: Int, _ v: Int) -> Int {
        precondition(0 <= u && u < n && 0 <= v && v < n, "no vertex \(u < 0 || u >= n ? u : v)")
        return u * n + v
    }

    /// one cell, however many neighbors u has
    public func hasEdge(_ u: Int, _ v: Int) -> Bool {
        cells[cell(u, v)]
    }

    @discardableResult
    public mutating func addEdge(_ u: Int, _ v: Int) -> Bool {
        if u == v || hasEdge(u, v) { return false }
        cells[cell(u, v)] = true
        cells[cell(v, u)] = true
        edges += 1
        return true
    }

    @discardableResult
    public mutating func removeEdge(_ u: Int, _ v: Int) -> Bool {
        guard hasEdge(u, v) else { return false }
        cells[cell(u, v)] = false
        cells[cell(v, u)] = false
        edges -= 1
        return true
    }

    /// reads u's whole row in order, so the neighbors come out smallest first: n cells, however few are set
    public func neighbors(_ u: Int) -> [Int] {
        (0..<n).filter { cells[cell(u, $0)] }
    }

    public func degree(_ u: Int) -> Int {
        neighbors(u).count
    }
}
python/algos/graph.py
"""graphs as data: one undirected graph on vertices 0 to n - 1, stored two ways. an adjacency list keeps each vertex's neighbors in an array of their own: n + 2m entries for m edges, and has edge scans one vertex's list. an adjacency matrix keeps an n by n grid of yes and no: n² cells, and has edge reads one. both turn away an edge from a vertex to itself, and an edge that's already there."""

from __future__ import annotations


def _check(n: int, *vs: int) -> None:
    """Raise IndexError for any vertex outside 0 to n - 1. Without it, a list would read -1 from its end."""
    for v in vs:
        if not 0 <= v < n:
            raise IndexError(f"no vertex {v}")


class AdjList:
    """A list of neighbors per vertex, in the order their edges went in."""

    def __init__(self, n: int) -> None:
        self._adj: list[list[int]] = [[] for _ in range(n)]  # [[]] * n would share one list
        self._edges = 0

    @property
    def vertices(self) -> int:
        """How many vertices there are: 0 to n - 1."""
        return len(self._adj)

    @property
    def edges(self) -> int:
        """How many edges there are."""
        return self._edges

    def has_edge(self, u: int, v: int) -> bool:
        """Scan u's list for v: one step per neighbor."""
        _check(self.vertices, u, v)
        return v in self._adj[u]

    def add_edge(self, u: int, v: int) -> bool:
        """Join u and v: each end goes on the other's list.

        Return False for u == v, or an edge that's already there.
        """
        if u == v or self.has_edge(u, v):
            return False
        self._adj[u].append(v)
        self._adj[v].append(u)
        self._edges += 1
        return True

    def remove_edge(self, u: int, v: int) -> bool:
        """Take each end off the other's list: the last neighbor moves into its place, so nothing shifts.

        Return False if there's no edge between u and v.
        """
        if not self.has_edge(u, v):
            return False
        for a, b in ((u, v), (v, u)):
            adj = self._adj[a]
            adj[adj.index(b)] = adj[-1]
            adj.pop()
        self._edges -= 1
        return True

    def neighbors(self, u: int) -> list[int]:
        """Return a copy of u's list: the vertices joined to u."""
        _check(self.vertices, u)
        return list(self._adj[u])

    def degree(self, u: int) -> int:
        """Return how many edges touch u: the length of its list."""
        _check(self.vertices, u)
        return len(self._adj[u])


class AdjMatrix:
    """An n by n grid: cell u, v is True when u and v are joined, and so is cell v, u.

    The grid is one flat list, row after row, so cell u, v is at u * n + v.
    """

    def __init__(self, n: int) -> None:
        self._n = n
        self._cells = [False] * (n * n)
        self._edges = 0

    @property
    def vertices(self) -> int:
        """How many vertices there are: 0 to n - 1."""
        return self._n

    @property
    def edges(self) -> int:
        """How many edges there are."""
        return self._edges

    def has_edge(self, u: int, v: int) -> bool:
        """Read one cell, however many neighbors u has."""
        _check(self._n, u, v)
        return self._cells[u * self._n + v]

    def add_edge(self, u: int, v: int) -> bool:
        """Join u and v: set cell u, v and cell v, u.

        Return False for u == v, or an edge that's already there.
        """
        if u == v or self.has_edge(u, v):
            return False
        self._cells[u * self._n + v] = True
        self._cells[v * self._n + u] = True
        self._edges += 1
        return True

    def remove_edge(self, u: int, v: int) -> bool:
        """Clear cell u, v and cell v, u. Return False if there's no edge between u and v."""
        if not self.has_edge(u, v):
            return False
        self._cells[u * self._n + v] = False
        self._cells[v * self._n + u] = False
        self._edges -= 1
        return True

    def neighbors(self, u: int) -> list[int]:
        """Read u's whole row: n cells, however few are set. The neighbors come out ascending."""
        _check(self._n, u)
        row = u * self._n  # where u's row starts
        return [v for v in range(self._n) if self._cells[row + v]]

    def degree(self, u: int) -> int:
        """Return how many edges touch u. It reads the whole row too."""
        return len(self.neighbors(u))

pitfalls

variants

practice

how real libraries do it

sources

  1. petgraph 0.8.3. Graph (opens in a new tab) uses an adjacency list representation in O(|V| + |E|) space, based on the graph data structure in rustc, and each node and edge (opens in a new tab) holds the next edge of its outgoing and incoming lists. MatrixGraph (opens in a new tab) is backed by a flattened 2d array, in O(|V|²) space, and stores only the lower triangle for an undirected graph. GraphMap (opens in a new tab) combines an adjacency list with a sparse adjacency matrix and tests for an edge in constant time. Csr (opens in a new tab) is compressed sparse row: one array holds the neighbors of every node, and another where each node’s row starts. ↩ ↩2 ↩3

  2. graph.py (opens in a new tab) in networkx 3.7: the Graph class uses a dict-of-dict-of-dict structure, an outer dict keyed by node, then a dict keyed by neighbor, then a dict of the edge’s attributes. add_edge (opens in a new tab) puts the same data dict under _adj[u][v] and _adj[v][u], and has_edge (opens in a new tab) checks v in self._adj[u]. ↩ ↩2