Programming Search⌘K

Conceptcore

Graph

Also called graph, graph data structure, network, adjacency list, adjacency matrix, directed graph, undirected graph, vertices and edges.

A graph is a set of nodes joined by edges, with no root and no limit on links. Programs store it as an adjacency list, a map from each node to its neighbors, or as a matrix.

Applies to
core-languages

Idea

A graph is a set of nodes and a set of links between them. Wikipedia: "A graph data structure consists of a finite (and possibly mutable) set of vertices (also called nodes or points), together with a set of unordered pairs of these vertices for an undirected graph or a set of ordered pairs for a directed graph."1 A tree is a graph with strict rules. A general graph has no root, a node can have many parents, and the links can form cycles.

Package dependencies, road maps, social networks, links between web pages and calls between functions are graphs. This program stores which part of an app needs which other part. It is a map from each node to a set of its neighbors.

from graphlib import TopologicalSorter

# Each key needs the parts in its set.
needs = {
    "app": {"web", "db"},
    "web": {"auth"},
    "auth": {"db"},
    "db": set(),
}

print("app needs:", sorted(needs["app"]))
print("does web need db?", "yes" if "db" in needs["web"] else "no")

used_by = {name: set() for name in needs}
for name, parts in needs.items():
    for part in parts:
        used_by[part].add(name)
print("db is used by:", sorted(used_by["db"]))

print("build order:", list(TopologicalSorter(needs).static_order()))
Output
app needs: ['db', 'web']
does web need db? no
db is used by: ['app', 'auth']
build order: ['db', 'auth', 'web', 'app']

The map gives the parts that a node needs at once. To find the parts that need a node, the program builds a second map, here used_by.

How it works

Vertices and edges. The nodes are also called vertices, and the links are edges. In a directed graph each edge has a direction, from one node to another. In an undirected graph an edge joins two nodes both ways. "A graph data structure may also associate to each edge some edge value, such as a symbolic label or a numeric attribute (cost, capacity, length, etc.)."1 A graph with such values is a weighted graph.

Operations. Wikipedia lists the basic operations.1 Among them:

  • adjacent(G, x, y) "tests whether there is an edge from the vertex x to the vertex y";
  • neighbors(G, x) "lists all vertices y such that there is an edge from the vertex x to the vertex y";
  • add_vertex, remove_vertex, add_edge and remove_edge.

Adjacency list. "Vertices are stored as records or objects, and every vertex stores a list of adjacent vertices."1 In most languages this is a map from a node to a list or a set of nodes. A set makes the edge test fast: Wikipedia notes that hash tables for the neighbor sets give "an amortized average time complexity of O(1) to test adjacency of two given vertices".1

Adjacency matrix. "A two-dimensional matrix, in which the rows represent source vertices and columns represent destination vertices."1 The nodes are numbered 0 to n minus 1, and cell [i][j] is true, or holds the weight, when there is an edge from i to j. "Only the cost for one edge can be stored between each pair of vertices."1

Which one. "Adjacency lists are generally preferred for the representation of sparse graphs, while an adjacency matrix is preferred if the graph is dense".1 Road maps and dependency graphs have few edges per node, so an adjacency list suits them.

Edge list. A plain list of (from, to) pairs is the simplest form. It is a good format to read and write, and programs usually turn it into an adjacency list before they work on it.

The algorithms that walk and search graphs are on the algorithm site: graph representation, breadth-first search, depth-first search and topological sort.

In languages

LanguageVerdictNote
PythonIdiom
C++Idiom
JavaIdiom
CIdiom
C#Idiom
JavaScriptIdiom
TypeScriptIdiomA Map from each node to an array or a Set of neighbors is an adjacency list, as in the JavaScript example. No example file exists.
GoIdiom
RustIdiom
KotlinIdiomA Map from each node to a List of neighbors is an adjacency list, as in Java. No example file exists because kotlinc is not installed.
SQLIdiomAn edge table with a source column and a target column stores a graph. Joins follow the edges.
BashIdiomAn associative array can map each node to a string of neighbor names. No example file exists.
PowerShellIdiomA hashtable from each node to an array of neighbors is an adjacency list. No example file exists because pwsh is not installed.
HTMLDoes not applyHTML is markup. Links between pages form a graph, but HTML has no data structures for a program.
CSSDoes not applyCSS style rules have no data structures.
Regular expressionsDoes not applyA regular expression matches text. It has no data structures.

No core language has a general graph type in its standard library. A program builds an adjacency list from a map and lists or sets, or it uses a graph library.

Language Verdict Form
Python idiom a dict of set or list; graphlib.TopologicalSorter2; the NetworkX library3
JavaScript idiom a Map from node to an array or a Set
TypeScript idiom as JavaScript, with Map<string, Set<string>>
Java idiom a Map<V, List<V>>; the JGraphT library4
C idiom an adjacency matrix of numbered nodes, or arrays of neighbor indexes
C++ idiom a std::vector<std::vector<int>> or a map of vectors; the Boost Graph Library5
C# idiom a Dictionary<TKey, List<TKey>>
Go idiom a map[string][]string
Rust idiom a HashMap or BTreeMap of Vec; the petgraph crate6
Kotlin idiom a Map of List, as in Java
PowerShell idiom a hashtable of arrays
Bash idiom an associative array from node to a string of neighbor names
SQL idiom an edge table with two node columns, and a node table
Regex n/a a pattern has no data structures
HTML/CSS n/a markup and style rules have no data structures

Python. The graphlib module has one class. TopologicalSorter "Provides functionality to topologically sort a graph of hashable nodes."2 Its input is a dictionary "where the keys are nodes and the values are iterables of all predecessors of that node in the graph".2 NetworkX is a library with graph types. Its documentation says that "The graph internal data structures are based on an adjacency list representation and implemented using Python dictionary datastructures."3

Java. JGraphT is "a Java library of graph theory data structures and algorithms".4 In it, "any object can be used for vertex and edge types, with full type safety via generics".4

C++. The Boost Graph Library defines "a generic interface that allows access to a graph's structure, but hides the details of the implementation."5

Rust. "petgraph is a graph data structure library."6 "Both nodes and edges can have arbitrary associated data, and edges may be either directed or undirected."6

The example files build the same directed graph of four nodes and five edges. They print the neighbors, test two edges and count the edges into one node.

PythonGitHub
edges = [("a", "b"), ("a", "c"), ("b", "c"), ("c", "d"), ("d", "a")]

graph = {}
for source, target in edges:
    graph.setdefault(source, []).append(target)
    graph.setdefault(target, [])

for node, neighbors in graph.items():
    print(node, "->", *neighbors)


def has_edge(x, y):
    return y in graph.get(x, [])


print("edge a->c:", "yes" if has_edge("a", "c") else "no")
print("edge c->a:", "yes" if has_edge("c", "a") else "no")
print("in-degree of c:", sum(neighbors.count("c") for neighbors in graph.values()))
print("edges:", sum(len(neighbors) for neighbors in graph.values()))
Output
a -> b c
b -> c
c -> d
d -> a
edge a->c: yes
edge c->a: no
in-degree of c: 2
edges: 5
  • Verdict: idiom. A dict from each node to a list of its neighbors is an adjacency list.
  • setdefault adds a node with an empty list the first time the node appears.
#include <algorithm>
#include <iostream>
#include <map>
#include <string>
#include <utility>
#include <vector>

int main() {
    std::vector<std::pair<std::string, std::string>> edges{
        {"a", "b"}, {"a", "c"}, {"b", "c"}, {"c", "d"}, {"d", "a"}};

    std::map<std::string, std::vector<std::string>> graph;
    for (const auto& [source, target] : edges) {
        graph[source].push_back(target);
        graph[target];
    }

    for (const auto& [node, neighbors] : graph) {
        std::cout << node << " ->";
        for (const auto& n : neighbors) {
            std::cout << ' ' << n;
        }
        std::cout << '\n';
    }

    auto has_edge = [&graph](const std::string& x, const std::string& y) {
        auto it = graph.find(x);
        return it != graph.end() &&
               std::find(it->second.begin(), it->second.end(), y) != it->second.end();
    };
    std::cout << "edge a->c: " << (has_edge("a", "c") ? "yes" : "no") << '\n';
    std::cout << "edge c->a: " << (has_edge("c", "a") ? "yes" : "no") << '\n';

    long in_degree = 0;
    std::size_t edge_count = 0;
    for (const auto& entry : graph) {
        in_degree += std::count(entry.second.begin(), entry.second.end(), "c");
        edge_count += entry.second.size();
    }
    std::cout << "in-degree of c: " << in_degree << '\n';
    std::cout << "edges: " << edge_count << '\n';
}
Output
a -> b c
b -> c
c -> d
d -> a
edge a->c: yes
edge c->a: no
in-degree of c: 2
edges: 5
  • Verdict: idiom. A std::map from each node to a std::vector of neighbors is an adjacency list. The map keeps its keys sorted.
  • graph[target]; creates an empty list for a node with no outgoing edges.
JavaGitHub
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        String[][] edges = {{"a", "b"}, {"a", "c"}, {"b", "c"}, {"c", "d"}, {"d", "a"}};

        Map<String, List<String>> graph = new LinkedHashMap<>();
        for (String[] edge : edges) {
            graph.computeIfAbsent(edge[0], k -> new ArrayList<>()).add(edge[1]);
            graph.computeIfAbsent(edge[1], k -> new ArrayList<>());
        }

        graph.forEach((node, neighbors) ->
                System.out.println(node + " -> " + String.join(" ", neighbors)));

        System.out.println("edge a->c: " + yesNo(hasEdge(graph, "a", "c")));
        System.out.println("edge c->a: " + yesNo(hasEdge(graph, "c", "a")));

        long inDegree = graph.values().stream()
                .flatMap(List::stream)
                .filter("c"::equals)
                .count();
        int edgeCount = graph.values().stream().mapToInt(List::size).sum();
        System.out.println("in-degree of c: " + inDegree);
        System.out.println("edges: " + edgeCount);
    }

    static boolean hasEdge(Map<String, List<String>> graph, String x, String y) {
        return graph.getOrDefault(x, List.of()).contains(y);
    }

    static String yesNo(boolean value) {
        return value ? "yes" : "no";
    }
}
Output
a -> b c
b -> c
c -> d
d -> a
edge a->c: yes
edge c->a: no
in-degree of c: 2
edges: 5
  • Verdict: idiom. A LinkedHashMap keeps the nodes in insertion order, and computeIfAbsent creates each list once.
  • For graph algorithms and weighted edges, a library such as JGraphT has graph types.
#include <stdbool.h>
#include <stdio.h>

#define N 4

static const char names[N] = {'a', 'b', 'c', 'd'};

int main(void) {
    int edges[][2] = {{0, 1}, {0, 2}, {1, 2}, {2, 3}, {3, 0}};
    int edge_count = (int)(sizeof edges / sizeof edges[0]);

    bool adjacent[N][N] = {{false}};
    for (int i = 0; i < edge_count; i++) {
        adjacent[edges[i][0]][edges[i][1]] = true;
    }

    for (int x = 0; x < N; x++) {
        printf("%c ->", names[x]);
        for (int y = 0; y < N; y++) {
            if (adjacent[x][y]) {
                printf(" %c", names[y]);
            }
        }
        printf("\n");
    }

    printf("edge a->c: %s\n", adjacent[0][2] ? "yes" : "no");
    printf("edge c->a: %s\n", adjacent[2][0] ? "yes" : "no");

    int in_degree = 0;
    int count = 0;
    for (int x = 0; x < N; x++) {
        for (int y = 0; y < N; y++) {
            if (adjacent[x][y]) {
                count++;
                if (y == 2) {
                    in_degree++;
                }
            }
        }
    }
    printf("in-degree of c: %d\n", in_degree);
    printf("edges: %d\n", count);
    return 0;
}
Output
a -> b c
b -> c
c -> d
d -> a
edge a->c: yes
edge c->a: no
in-degree of c: 2
edges: 5
  • Verdict: idiom. The nodes are numbered 0 to 3, and a two-dimensional bool array is the adjacency matrix.
  • The edge test reads one cell. Listing the neighbors of a node reads a whole row.
(string From, string To)[] edges = [("a", "b"), ("a", "c"), ("b", "c"), ("c", "d"), ("d", "a")];

var order = new List<string>();
var graph = new Dictionary<string, List<string>>();
foreach (var (from, to) in edges)
{
    foreach (string node in new[] { from, to })
    {
        if (!graph.ContainsKey(node))
        {
            graph[node] = new List<string>();
            order.Add(node);
        }
    }
    graph[from].Add(to);
}

foreach (string node in order)
{
    Console.WriteLine(node + " -> " + string.Join(" ", graph[node]));
}

bool HasEdge(string x, string y) => graph.TryGetValue(x, out var neighbors) && neighbors.Contains(y);

Console.WriteLine("edge a->c: " + (HasEdge("a", "c") ? "yes" : "no"));
Console.WriteLine("edge c->a: " + (HasEdge("c", "a") ? "yes" : "no"));
Console.WriteLine("in-degree of c: " + graph.Values.Sum(neighbors => neighbors.Count(n => n == "c")));
Console.WriteLine("edges: " + graph.Values.Sum(neighbors => neighbors.Count));
Output
a -> b c
b -> c
c -> d
d -> a
edge a->c: yes
edge c->a: no
in-degree of c: 2
edges: 5
  • Verdict: idiom. A Dictionary<string, List<string>> is an adjacency list. The program keeps a separate list of the nodes, so it prints them in the order they were added.
  • TryGetValue gives false for a node that is not in the graph.
JavaScriptGitHub
const edges = [["a", "b"], ["a", "c"], ["b", "c"], ["c", "d"], ["d", "a"]];

const graph = new Map();
for (const [source, target] of edges) {
  if (!graph.has(source)) graph.set(source, []);
  if (!graph.has(target)) graph.set(target, []);
  graph.get(source).push(target);
}

for (const [node, neighbors] of graph) {
  console.log(`${node} -> ${neighbors.join(" ")}`);
}

const hasEdge = (x, y) => (graph.get(x) ?? []).includes(y);
const yesNo = (value) => (value ? "yes" : "no");

console.log("edge a->c:", yesNo(hasEdge("a", "c")));
console.log("edge c->a:", yesNo(hasEdge("c", "a")));

let inDegree = 0;
let edgeCount = 0;
for (const neighbors of graph.values()) {
  inDegree += neighbors.filter((n) => n === "c").length;
  edgeCount += neighbors.length;
}
console.log("in-degree of c:", inDegree);
console.log("edges:", edgeCount);
Output
a -> b c
b -> c
c -> d
d -> a
edge a->c: yes
edge c->a: no
in-degree of c: 2
edges: 5
  • Verdict: idiom. A Map from each node to an array of neighbors is an adjacency list.
  • The in-degree needs a scan of every list, because the map stores only outgoing edges.
package main

import (
	"fmt"
	"slices"
	"strings"
)

func main() {
	edges := [][2]string{{"a", "b"}, {"a", "c"}, {"b", "c"}, {"c", "d"}, {"d", "a"}}

	graph := map[string][]string{}
	var order []string
	for _, e := range edges {
		for _, node := range e {
			if _, ok := graph[node]; !ok {
				graph[node] = []string{}
				order = append(order, node)
			}
		}
		graph[e[0]] = append(graph[e[0]], e[1])
	}

	for _, node := range order {
		fmt.Println(node, "->", strings.Join(graph[node], " "))
	}

	hasEdge := func(x, y string) bool {
		return slices.Contains(graph[x], y)
	}
	yesNo := func(b bool) string {
		if b {
			return "yes"
		}
		return "no"
	}
	fmt.Println("edge a->c:", yesNo(hasEdge("a", "c")))
	fmt.Println("edge c->a:", yesNo(hasEdge("c", "a")))

	inDegree, edgeCount := 0, 0
	for _, neighbors := range graph {
		for _, n := range neighbors {
			if n == "c" {
				inDegree++
			}
		}
		edgeCount += len(neighbors)
	}
	fmt.Println("in-degree of c:", inDegree)
	fmt.Println("edges:", edgeCount)
}
Output
a -> b c
b -> c
c -> d
d -> a
edge a->c: yes
edge c->a: no
in-degree of c: 2
edges: 5
  • Verdict: idiom. A map[string][]string is an adjacency list. The program keeps the nodes in a slice to print them in a fixed order.
  • slices.Contains tests for an edge.
RustGitHub
use std::collections::BTreeMap;

fn main() {
    let edges = [("a", "b"), ("a", "c"), ("b", "c"), ("c", "d"), ("d", "a")];

    let mut graph: BTreeMap<&str, Vec<&str>> = BTreeMap::new();
    for (source, target) in edges {
        graph.entry(source).or_default().push(target);
        graph.entry(target).or_default();
    }

    for (node, neighbors) in &graph {
        println!("{node} -> {}", neighbors.join(" "));
    }

    let has_edge = |x: &str, y: &str| graph.get(x).is_some_and(|n| n.contains(&y));
    let yes_no = |b: bool| if b { "yes" } else { "no" };
    println!("edge a->c: {}", yes_no(has_edge("a", "c")));
    println!("edge c->a: {}", yes_no(has_edge("c", "a")));

    let in_degree: usize = graph
        .values()
        .map(|n| n.iter().filter(|t| **t == "c").count())
        .sum();
    let edge_count: usize = graph.values().map(Vec::len).sum();
    println!("in-degree of c: {in_degree}");
    println!("edges: {edge_count}");
}
Output
a -> b c
b -> c
c -> d
d -> a
edge a->c: yes
edge c->a: no
in-degree of c: 2
edges: 5
  • Verdict: idiom. A BTreeMap from each node to a Vec of neighbors is an adjacency list, with the keys in sorted order.
  • entry(...).or_default() creates an empty list the first time a node appears.
  • Directed acyclic graph. A directed graph with no cycles. Build systems and package managers use one for dependencies. A topological order exists only for such a graph: "A complete topological ordering is possible if and only if the graph has no directed cycles".2 See dependency-resolution.
  • Multigraph. More than one edge can join the same two nodes. NetworkX has MultiGraph, "A flexible graph class that allows multiple undirected edges between pairs of nodes."3 A multimap can store one.
  • Tree. A connected graph where each node except the root has one parent. See tree-concept.
  • Implicit graph. The edges are computed, not stored. The squares of a game board and the states of a puzzle are graphs of this kind.
  • Graph databases. Some databases store nodes and edges as their main model and query paths directly.

Pitfalls

An undirected edge stored in one direction

In an adjacency list, an undirected edge must appear in the lists of both nodes. If the program adds it only once, the graph becomes directed by mistake.

This code runs but gives a wrong answer on purpose.

friends = {"ana": set(), "ben": set(), "cho": set()}


def add_friend(a, b):
    friends[a].add(b)


add_friend("ana", "ben")
print("ben in ana's friends:", "yes" if "ben" in friends["ana"] else "no")
print("ana in ben's friends:", "yes" if "ana" in friends["ben"] else "no")
Output
ben in ana's friends: yes
ana in ben's friends: no

Add both directions in one function, so no caller can forget the second one:

friends = {"ana": set(), "ben": set(), "cho": set()}


def add_friend(a, b):
    friends[a].add(b)
    friends[b].add(a)


add_friend("ana", "ben")
print("ana in ben's friends:", "yes" if "ana" in friends["ben"] else "no")
Output
ana in ben's friends: yes

Walking a graph as if it were a tree

A recursive walk over the children of a tree ends at the leaves. In a graph with a cycle, the same walk never ends, because it comes back to a node it has already seen.

This code runs but gives a wrong answer on purpose.

links = {"home": ["about"], "about": ["contact"], "contact": ["home"]}


def count_pages(page):
    return 1 + sum(count_pages(nxt) for nxt in links[page])


try:
    print(count_pages("home"))
except RecursionError:
    print("RecursionError")


def count_pages_seen(start):
    seen = set()
    stack = [start]
    while stack:
        page = stack.pop()
        if page not in seen:
            seen.add(page)
            stack.extend(links[page])
    return len(seen)


print("pages:", count_pages_seen("home"))
Output
RecursionError
pages: 3

Keep a set of visited nodes. Without it, a graph that has no cycle but has shared nodes is still slow, because the walk visits a shared node once for each path to it.

A matrix for a sparse graph

An adjacency matrix has one cell for each pair of nodes, whether or not an edge exists. Wikipedia gives the storage of a matrix as the square of the number of vertices, and the storage of an adjacency list as the number of vertices plus the number of edges.1 A road map with a million junctions and a few roads at each junction needs a million million cells as a matrix, but only a few million entries as an adjacency list.

Cost

Wikipedia gives these costs, with V vertices and E edges.1

Operation Adjacency list Adjacency matrix
store the graph V + E V squared
add a vertex constant V squared
add an edge constant constant
remove a vertex E V squared
remove an edge V constant
test if x and y are adjacent V constant

With hash sets for the neighbors, the edge test and the edge removal become constant on average.1

History

The Python graphlib documentation marks the module's class with "Added in version 3.9."2

References

  1. Graph (abstract data type), Wikipedia, the introduction; Operations; Common data structures for graph representation
  2. graphlib, Functionality to operate with graph-like structures, Python documentation, TopologicalSorter; CycleError
  3. Introduction, NetworkX documentation, NetworkX Basics; Graphs
  4. JGraphT, the home page
  5. The Boost Graph Library (BGL), Boost 1.89.0, the introduction
  6. Crate petgraph, docs.rs, the crate description

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/AVZZ4W/text.yaml