# graphs as data

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

source: https://learning.anthnydas.com/ds/graph/

## tl;dr

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

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

> **interactive figure:** 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.

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.

the same graph as adjacency lists: a row per vertex, holding its neighbors in the order their edges went in. row 1 holds 0, 2 and 3. each edge is on two rows, so 7 edges make 14 entries.

as an adjacency matrix: 6 by 6, with a 1 at row u, column v when u and v are joined. the edge 1, 3 sets row 1, column 3, and row 3, column 1: the matrix is the same flipped across its diagonal, and the diagonal stays 0.

add the edge 1, 4: 4 goes on the end of row 1, and 1 on the end of row 4. in the matrix, two cells turn to 1.

has edge 2, 5? the lists scan row 2 an entry at a time: 0, 1, 4. no 5, and it took all 3 to be sure. the matrix reads one cell, row 2, column 5: 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?

- **adjacency lists.** a list per vertex, holding its neighbors. an edge between u and v puts v on u's list and u on v's list, so m edges make 2m entries, plus a row for each of the n vertices. u's neighbors are u's list, and how many it has is its length: u's degree, deg u for short. is there an edge to v means scanning u's list for it
- **adjacency matrix.** an n by n grid of yes and no. cell u, v is 1 when u and v are joined, and an edge sets two cells, u, v and v, u. is there an edge is one cell. but the grid has n² cells before a single edge goes in, and listing u's neighbors means reading all n cells of its row

## the operations

> **interactive figure:** 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

> **interactive figure:** 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

```text
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.

> **interactive figure:** 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.

- **sparse graphs.** most graphs in the wild: roads, friendships, links between pages. each vertex has a few neighbors however many vertices there are, so the lists grow with n. the matrix grows with n² anyway. a million vertices with 4 neighbors each make 5,000,000 list entries. the matrix would have 1,000,000,000,000 cells, 125 gigabytes even at a bit a cell, and all but 4,000,000 of them 0
- **dense graphs.** when most pairs are joined, the lists hold about as many entries as the matrix has cells. with every pair joined it's exactly n² both ways, since each vertex's row holds the other n - 1. a cell needs only a bit, though, where an entry holds a whole vertex number, so a dense graph is smaller as a matrix, and has edge stays one step

## complexity

| operation   | lists            | matrix |
| ----------- | ---------------- | ------ |
| has edge    | O(deg u)         | O(1)   |
| add edge    | O(deg u)         | O(1)   |
| remove edge | O(deg u + deg v) | O(1)   |
| neighbors   | O(deg u)         | O(n)   |
| degree      | O(1)             | O(n)   |
| memory      | O(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](/ds/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`

```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`

```rust
//! 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`

```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`

```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`

```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`

```python
"""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

- **one end only.** an edge with no direction is on two lists and in two cells. add or remove only one, and u is joined to v while v isn't joined to u
- **repeats.** without a has edge check first, adding an edge twice puts v on u's list twice, and u's degree is off by one. the matrix can't hold a repeat: the cell is 1 already
- **a matrix for a big sparse graph.** n² cells come before a single edge. a million vertices is 1,000,000,000,000 cells
- **counting on the order.** a row's order is the order its edges went in, until a remove moves the last neighbor into a hole. if the order matters, sort the row, or read the matrix, which goes in order
- **every edge from the matrix.** listing all the edges reads all n² cells, however few edges there are. from the lists it's n + 2m

## variants

- **directed graphs.** an edge goes one way: u's list gets v, and v's list doesn't get u. the matrix sets one cell, so it stops being the same across its diagonal. links between pages, or tasks and what each one needs first, are directed
- **weighted graphs.** each edge carries a number, a distance or a cost. a list entry holds the neighbor and the weight, and a cell holds the weight in place of the 1, with some value set aside to mean no edge. dijkstra's shortest paths needs one
- **an edge list.** just the m pairs, in an array: nothing to look up by vertex, but it's how graphs usually arrive in a file, and what kruskal's minimum spanning tree sorts
- **compressed sparse row.** every row of the lists, one after another in one array, and a second array of where each row starts: 2m entries and n + 1 offsets, with nothing per row to spare. it suits a graph that's built once and read many times. petgraph's `Csr` is one[^petgraph]
- **hash-set rows.** keep each vertex's neighbors in a hash set, and has edge is O(1) on average, with memory that still follows the edges. networkx does this with dicts[^networkx]
- **half a matrix.** cell u, v and cell v, u always match, so the cells on one side of the diagonal are enough. petgraph's `MatrixGraph` keeps only the lower half for a graph with no directions[^petgraph]
- **a bit matrix.** a cell is yes or no, so it fits in one bit, 64 cells to a 64-bit word. has edge is still one read

## practice

- [find center of star graph](https://leetcode.com/problems/find-center-of-star-graph/): the one vertex on every edge
- [find the town judge](https://leetcode.com/problems/find-the-town-judge/): count the edges in and out of each vertex, in a directed graph
- [maximal network rank](https://leetcode.com/problems/maximal-network-rank/): degrees, plus has edge for every pair
- [find if path exists in graph](https://leetcode.com/problems/find-if-path-exists-in-graph/): build the lists from an edge list, then walk them
- [keys and rooms](https://leetcode.com/problems/keys-and-rooms/): the input is the lists already
- [clone graph](https://leetcode.com/problems/clone-graph/): copy a graph whose vertices hold their own neighbors

## how real libraries do it

- **networkx.** a `Graph` is a dict of dicts of dicts: each vertex maps to a dict of its neighbors, and each neighbor to a dict of the edge's data, shared by both ends. has edge is a dict lookup: adjacency lists with hash-set rows[^networkx]
- **petgraph.** `Graph` is adjacency lists, threaded through two arrays: each vertex holds its first edge, and each edge the next one at each of its ends. `MatrixGraph` is an adjacency matrix in one flat array. `GraphMap` keys the vertices in a hash map and finds an edge in constant time, and `Csr` packs every row into one array[^petgraph]
- **the standard libraries.** none of python, go, rust, java, swift or c has a general graph type. a list of lists, or a map from each vertex to its neighbors, covers most code

[^networkx]: [graph.py](https://github.com/networkx/networkx/blob/networkx-3.7/networkx/classes/graph.py#L232-L236) 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`](https://github.com/networkx/networkx/blob/networkx-3.7/networkx/classes/graph.py#L979-L982) puts the same data dict under `_adj[u][v]` and `_adj[v][u]`, and [`has_edge`](https://github.com/networkx/networkx/blob/networkx-3.7/networkx/classes/graph.py#L1339) checks `v in self._adj[u]`.

[^petgraph]: petgraph 0.8.3. [`Graph`](https://github.com/petgraph/petgraph/blob/petgraph%40v0.8.3/src/graph_impl/mod.rs#L319-L336) uses an adjacency list representation in O(|V| + |E|) space, based on the graph data structure in rustc, and [each node and edge](https://github.com/petgraph/petgraph/blob/petgraph%40v0.8.3/src/graph_impl/mod.rs#L218-L251) holds the next edge of its outgoing and incoming lists. [`MatrixGraph`](https://github.com/petgraph/petgraph/blob/petgraph%40v0.8.3/src/matrix_graph.rs#L223-L241) is backed by a flattened 2d array, in O(|V|²) space, and stores only the lower triangle for an undirected graph. [`GraphMap`](https://github.com/petgraph/petgraph/blob/petgraph%40v0.8.3/src/graphmap.rs#L50-L56) combines an adjacency list with a sparse adjacency matrix and tests for an edge in constant time. [`Csr`](https://github.com/petgraph/petgraph/blob/petgraph%40v0.8.3/src/csr.rs#L55-L84) is compressed sparse row: one array holds the neighbors of every node, and another where each node's row starts.

## related

- https://learning.anthnydas.com/algos/bfs.md
- https://learning.anthnydas.com/algos/dfs.md
- https://learning.anthnydas.com/algos/dijkstra.md
- https://learning.anthnydas.com/ds/union-find.md
- https://learning.anthnydas.com/ds/hash-table.md
- https://learning.anthnydas.com/ds/dynamic-array.md
