What is a Graph

A graph is a set of nodes plus a set of edges connecting them. Direction, weight and cycles are all variations on those two sets.

Every structure so far has stored values. A graph stores the relationships between values: the nodes are the things, and the edges say how they relate.

The subway map analogy

Look at a subway map. The stations are nodes. The tracks between them are edges. The map tells you nothing about how far apart the stations really are, and it doesn't need to, because what you want to know is which stations connect to which. A graph works the same way: the connections are the data.

An undirected graph with 6 nodes and 6 edges
ABCDEF

six nodes, six edges and one cycle: A–B–D–C–A

A graph is an abstract data type (ADT), not a concrete data structure. It defines what you can ask (add a node, connect two nodes, list a node's neighbors) and says nothing about how any of it is stored. Two concrete structures honor that contract, the adjacency list and the adjacency matrix, and choosing between them is the most consequential decision you make about a graph. Most of this article is about that choice.

A graph also has no first element, no last element and no order. A linked list is a graph where every node has exactly one neighbor; a tree is a graph with no cycles and one root. Graphs are the general case, and every structure in this series so far is a graph with extra rules.

The problem previous structures couldn't solve

Every structure so far imposes a shape on your data, and each shape has a matching question it answers well.

Arrays index by position. Position is a useful relationship when your data really is sequential, but "user 4 is next to user 5" says nothing about whether they know each other.

Linked lists chain one node to the next. That's a relationship, but only one per node and always in one direction. You can't express "this station connects to three other stations."

Hash tables map a key to a value in O(1). That's the closest fit among the flat structures, and it's why graphs are usually built on one. But a hash table on its own stores key → value, not key → other keys.

Trees get closest of all, and the last six articles were variations on them. A tree finally lets one node point at many, but it pays for that with two restrictions it never relaxes: every node has exactly one parent, and there are no cycles. A tree's guarantees depend on both, and real relationships break both.

None of them can express many-to-many relationships with cycles. A person has many friends, each of whom has many friends, and if you follow those links far enough you come back to where you started. Graphs exist for this case, and you get one by dropping a tree's two restrictions.

Nodes, edges, and the vocabulary

Graphs come with more vocabulary than any structure so far. All of it describes the same two sets, so the fastest way through is to keep the same six nodes and change one thing at a time.

Vertices and edges

A node of a graph is also called a vertex (plural vertices). The two words mean the same thing: "node" is more common in code, "vertex" in math books and papers. An edge is a connection between two vertices, written as the pair it joins, like (A, B). Those two vertices are the edge's endpoints, and two vertices joined by an edge are adjacent, or neighbors. In the graph above, A and C are adjacent; A and D are not, even though a path connects them through B.

That gives the formal definition its usual shape: a graph is a pair G = (V, E), where V is the set of vertices and E is the set of edges. When a cost depends on the size of the graph, the same letters stand for the counts. O(V + E) means "proportional to the number of vertices plus the number of edges", and the graph above has V = 6 and E = 6. The rest of this article uses the letters that way.

Directed vs undirected

In an undirected graph, an edge is mutual: if A connects to B, then B connects to A. Facebook friendship works this way: there's no such thing as a one-way friend.

In a directed graph (or digraph), each edge has a direction. A points to B says nothing about whether B points to A. Twitter follows work this way, as do web links, task dependencies, and function calls.

The same nodes, now directed
ABCin 2 · out 0DEF

D is reachable from A, but A is not reachable from D

Direction also changes what the structure stores. An undirected edge is recorded twice, once in each endpoint's neighbor list, while a directed edge is recorded once. That doubling is why an undirected adjacency list costs 2E slots instead of E.

In a directed graph each node has two counts: in-degree (edges arriving) and out-degree (edges leaving). D above has in-degree 2 and out-degree 0.

Weighted vs unweighted

An edge can carry a number: distance, cost, capacity, latency, similarity. A graph whose edges carry numbers is weighted.

The same graph, now weighted
412735ABCDEF

A–B–D costs 6 and A–C–D costs 8, so counting edges doesn't tell you the cost

Structurally, a weight is just a second value stored alongside each edge. In an adjacency list the neighbor entry becomes a small struct instead of a bare id; in a matrix the cell holds a number instead of a bool, with a sentinel such as math.MaxInt (or 0, when zero can't be a legitimate weight) standing for "no edge."

The caption shows why weights are worth the extra field: A–C–D is two edges, the same as A–B–D, but it costs more. Once edges have different costs, "fewest edges" and "cheapest route" become different questions.

Degree, path, and cycle

A node's degree is how many edges touch it. A path is a sequence of nodes where each consecutive pair is connected. A simple path never repeats a node. A cycle is a path that ends where it began.

The cycle A–B–D–C–A, highlighted
2A2B3C2D2E1F

badges show each node's degree: C has 3, F has 1

Degree decides how expensive a node is to work with: an adjacency list answers "who are this node's neighbors" in time proportional to its degree, so a high-degree node is a slow node. In a social graph that's the celebrity problem, where a few accounts with millions of edges dominate the cost of everything.

Cycles separate a graph from a tree. Because D is reachable from A two different ways, there is no single parent relationship to lean on, and no guarantee that following edges ever ends. A graph with direction and no cycles is a DAG (directed acyclic graph), the shape dependency data takes.

Connected, disconnected, and components

A graph is connected if there's a path between every pair of nodes. If not, it splits into connected components: islands with no edges between them.

Two components: G is unreachable
ABCDE0G

no path from A reaches G, but G is still part of the graph

G matters for the representation even though nothing points at it. An adjacency list still needs an entry for it (that's the V in O(V + E)), and a matrix still allocates its whole row and column. A node with no edges costs you something in both layouts, so the node count always matters.

Representing a Graph in memory

Two structures dominate, and the choice between them is a trade of space against lookup speed.

Adjacency list

Store, for each node, a list of its neighbors. In Go that's a map from node to slice of nodes.

For the graph above, the adjacency list is:

The graph above, stored as an adjacency list

As a graph

ABCDEF

Adjacency list (map[string][]string)

ABC
BAD
CADE
DBC
ECF
FE
V + 2E = 6 + 12 = 18 slots: every edge is stored at both ends. Hover an edge or a node to find it in the list, or click to keep it.

Each undirected edge appears twice, once from each end: A–B shows up in A's list and in B's. The duplicate is what makes "list B's neighbors" as fast as "list A's."

Here's the type and how to use it, with the implementation in the second tab.

package mainimport "fmt"func main() {    g := NewGraph()    g.AddEdge("A", "B")    g.AddEdge("A", "C")    g.AddEdge("B", "D")    g.AddEdge("C", "D")    g.AddEdge("C", "E")    g.AddEdge("E", "F")    fmt.Println(g.Neighbors("A"))    // [B C]    fmt.Println(g.HasEdge("A", "D")) // false    fmt.Println(g.Degree("C"))       // 3    fmt.Println(len(g.Nodes()))      // 6    g.AddNode("G") // isolated, but still part of the graph    fmt.Println(len(g.Nodes()))      // 7}

The space cost is O(V + E): one map entry per node and one slice element per edge-end. For most real graphs that's small, because most real graphs are sparse: a Facebook user has hundreds of friends, not two billion.

Adjacency matrix

Store a V × V grid where cell [i][j] says whether an edge runs from i to j.

The same graph as a list and as a matrix

As a graph

ABCDEF

Adjacency list (map[string][]string)

ABC
BAD
CADE
DBC
ECF
FE

Adjacency matrix ([][]bool)

ABCDEF
A11000
B10100
C10110
D01100
E00101
F00001
list: V + 2E = 6 + 12 = 18 slots · matrix: V² = 36 cells. Hover an edge or a node to find it in each view, or click to keep it.

The matrix is symmetric across the diagonal because the graph is undirected; a digraph's matrix wouldn't be. It's also mostly zeros: 12 of 36 cells carry an edge, and that ratio only gets worse as the graph grows.

package mainimport "fmt"func main() {    m := NewMatrixGraph([]string{"A", "B", "C", "D", "E", "F"})    m.AddEdge("A", "B")    m.AddEdge("A", "C")    m.AddEdge("B", "D")    m.AddEdge("C", "D")    m.AddEdge("C", "E")    m.AddEdge("E", "F")    // One array read, whatever the node's degree.    fmt.Println(m.HasEdge("A", "B")) // true    fmt.Println(m.HasEdge("A", "D")) // false    // The cost of that: listing neighbors scans a whole row.    fmt.Println(m.Neighbors("C")) // [A D E]}
VMatrix cells (V²)
1,0001,000,000
100,00010,000,000,000
1,000,0001,000,000,000,000

Which one to use

OperationAdjacency listAdjacency matrix
Space
hasEdge(u, v)
Iterate neighbors
Add edge
Add node

A graph is dense when E approaches V², and sparse otherwise. The crossover between the two representations is exact: an undirected adjacency list holds V + 2E slots, so on a complete graph, where E = V(V−1)/2, that comes to V + V(V−1), which is exactly V², the matrix's cell count.

Counted in slots, the list is smaller for every graph that isn't complete and ties when it is. It only loses in practice because its slots are fatter: a slice header and a map bucket cost far more per entry than one byte in a grid. So a matrix wins when the graph is near-complete or small, or when hasEdge is your hot path, and a list wins everywhere else.

In practice adjacency lists win almost always, because the graphs people actually have (road networks, social graphs, dependency trees, the web) are sparse.

Try it yourself

Pick two nodes and add or remove the edge between them, or edit the drawing itself: drag from one node to another to connect them, click a line to cut it, click a matrix cell to flip it. Every edit updates the list, the matrix and the line under them that counts what each one stores. Has edge? asks the same question of both: the matrix answers with one read, while the list reads the first node's slice one entry at a time.

The matrix can work as a control because each cell is the question "is there an edge between these two," so changing a cell's answer and editing the graph are the same action. The adjacency list has no cell to click for an edge that doesn't exist, which is why it costs less.

Try Connect everything to reach the exact tie described above, then cut a single line and watch the list drop below the matrix again.

Your graph5 edges of 10
2A2B3C2D1E

drag between nodes to connect · click an edge to cut it · badges show degree

adjacency list

ABC
BAD
CADE
DBC
EC

adjacency matrix

ABCDE
A
B
C
D
E

list: V + 2E = 5 + 10 = 15 slots · matrix: V² = 25 cells

100%
Operation log
  1. every step of the next run shows up here

pick two nodes and add, remove or look up their edge · or edit the drawing and the matrix directly

Common operations and their costs

Assuming an adjacency list, where V is nodes and E is edges:

OperationCostWhy
Add nodeOne map insert
Add edgeAppend to one neighbor list, or two if undirected
Remove edgeMust scan the neighbor list to locate it
Remove nodeEvery other neighbor list may reference it
hasEdge(u, v)No index into the list; a matrix does this in O(1)
degree(u)Just the slice length
Iterate neighborsThe list holds precisely what you asked for
SpaceOne entry per node, one slot per edge-end

Many of these are O(deg) instead of O(1) or O(n). Degree is the adjacency list's characteristic cost, which is why a graph's shape, and not only its size, determines how fast your code runs.

Graphs in the real world

Social networks. People are nodes, relationships are edges. Facebook built a dedicated distributed graph store, TAO, because a social graph's read pattern (fetch one node's neighbors, millions of times a second) is what a general-purpose database is bad at. The bottleneck they engineered around was the representation.

Maps and routing. Intersections are nodes, roads are weighted edges. Road networks are extremely sparse (an intersection has maybe four roads, never four million), so they're stored as adjacency lists, usually in a compressed layout that trades editability for sequential reads.

Package managers and build systems. go mod graph prints a dependency graph, and every package manager keeps one. The DAG shape matters here: dependencies with no cycles admit a valid install order, and a cycle is reported as a hard error.

Compilers. Compilers turn each function into a control-flow graph: basic blocks as nodes, possible jumps as edges. These graphs are small and often dense enough that a bitset-backed matrix is the right call. That's the opposite choice from a road network, made for the reverse reasons.

Knowledge and recommendation graphs. Products, tags, users and their interactions form a graph where an edge means "related." Databases like Neo4j exist because expressing this in SQL means one join per hop, and the number of hops is exactly what you don't know ahead of time.

Databases. PostgreSQL keeps a wait-for graph of which transaction is blocked on which lock. It's a small directed graph maintained continuously, and a cycle in it is what tells the database a deadlock has occurred.

When Graphs fall short

Graphs model almost anything, which makes them easy to reach for when something simpler would do.

Pointer chasing is cache-hostile. Walking an adjacency list means following map lookups and slice references scattered across memory, so nearly every step is a cache miss. Arrays win on locality by a wide margin, which is why serious graph processing gives up the friendly representation for compressed formats like CSR, which pack all the neighbor lists into two flat arrays and give up cheap mutation to get sequential reads back.

Matrices don't scale. O(V²) is fine at a thousand nodes and impossible at a million, and the edge count never enters it. Reach for a matrix only when you've established the graph is dense and bounded.

High-degree nodes skew everything. O(deg) is a comfortable bound until one node has a million edges. Real graphs follow power laws, so a handful of nodes dominate the cost of every operation, and the average degree tells you almost nothing about the worst case.

Mutation and concurrency don't mix. A Go map isn't safe for concurrent write, so a shared graph needs a mutex or a redesign. A read that holds a lock while it walks serializes everything, and one that doesn't can see an edge list change underneath it. Immutable snapshots are usually the answer.

Something simpler often fits. If your data has one root and no cycles, it's a tree, and tree code is shorter and faster. If you only ever ask "what is this node's parent," a hash table of parents beats a graph. Use a graph when you actually need arbitrary many-to-many relationships; data that merely has some relationships in it doesn't need one.

Summary

Graphs are the general case that every other structure in this series is a special case of:

  • Nodes and edges: a graph models relationships instead of sequence, and expresses many-to-many connections that nothing else here can
  • Direction and weight are storage decisions: an undirected edge is stored twice, and a weight is an extra field per edge or per cell
  • Adjacency list for sparse, matrix for dense: O(V + E) against O(V²), and the crossover is exactly a complete graph
  • Degree is the cost that matters: most adjacency-list operations are O(deg), so the graph's shape, and not only its size, sets your performance
  • Cycles separate a graph from a tree: no root, no order, and no guarantee that following edges terminates

Arrays, linked lists, stacks, queues and hash tables all organize values. A graph organizes the connections between them, which is why picking a representation matters more here than for any structure so far: the same graph stored two ways can differ by orders of magnitude in memory and in the cost of the question you ask most.