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.
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.
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.
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.
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.
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:
As a graph
Adjacency list (map[string][]string)
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}package mainimport "sort"// Graph is an undirected graph stored as an adjacency list.// The zero value is not usable — call NewGraph.type Graph struct { adjacency map[string][]string}func NewGraph() *Graph { return &Graph{adjacency: make(map[string][]string)}}func (g *Graph) AddNode(id string) { if _, exists := g.adjacency[id]; !exists { g.adjacency[id] = nil }}func (g *Graph) AddEdge(from, to string) { g.AddNode(from) g.AddNode(to) // Recorded from both ends, which is what costs 2E rather than E. g.adjacency[from] = append(g.adjacency[from], to) g.adjacency[to] = append(g.adjacency[to], from)}func (g *Graph) Neighbors(id string) []string { return g.adjacency[id]}func (g *Graph) Degree(id string) int { return len(g.adjacency[id])}// HasEdge is O(degree) — there is no index into a neighbor list.func (g *Graph) HasEdge(from, to string) bool { for _, n := range g.adjacency[from] { if n == to { return true } } return false}// Nodes sorts because Go randomizes map iteration order, so an// unsorted result would differ between runs and quietly break any// caller that assumed otherwise.func (g *Graph) Nodes() []string { ids := make([]string, 0, len(g.adjacency)) for id := range g.adjacency { ids = append(ids, id) } sort.Strings(ids) return ids}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.
As a graph
Adjacency list (map[string][]string)
Adjacency matrix ([][]bool)
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]}package main// MatrixGraph is an undirected graph stored as an adjacency matrix.// Nodes are fixed at construction: adding one means reallocating the// whole grid, which is the price of an O(1) HasEdge.type MatrixGraph struct { ids []string index map[string]int cells [][]bool}func NewMatrixGraph(ids []string) *MatrixGraph { index := make(map[string]int, len(ids)) for i, id := range ids { index[id] = i } cells := make([][]bool, len(ids)) for i := range cells { cells[i] = make([]bool, len(ids)) } return &MatrixGraph{ids: ids, index: index, cells: cells}}func (m *MatrixGraph) AddEdge(from, to string) { i, okFrom := m.index[from] j, okTo := m.index[to] if !okFrom || !okTo { return } // Both cells, mirroring the undirected edge across the diagonal. m.cells[i][j] = true m.cells[j][i] = true}func (m *MatrixGraph) HasEdge(from, to string) bool { i, okFrom := m.index[from] j, okTo := m.index[to] if !okFrom || !okTo { return false } return m.cells[i][j]}// Neighbors is O(V): the row has a cell per node, not per neighbor.func (m *MatrixGraph) Neighbors(id string) []string { i, ok := m.index[id] if !ok { return nil } var found []string for j, connected := range m.cells[i] { if connected { found = append(found, m.ids[j]) } } return found}| V | Matrix cells (V²) |
|---|---|
| 1,000 | 1,000,000 |
| 100,000 | 10,000,000,000 |
| 1,000,000 | 1,000,000,000,000 |
Which one to use
| Operation | Adjacency list | Adjacency 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.
drag between nodes to connect · click an edge to cut it · badges show degree
adjacency list
adjacency matrix
list: V + 2E = 5 + 10 = 15 slots · matrix: V² = 25 cells
Keyboard and mouse
- M
- sound on or off
- F
- fullscreen
- R
- reset
- Space+drag
- move the canvas
- Ctrl+scroll
- zoom
- every step of the next run shows up here
Common operations and their costs
Assuming an adjacency list, where V is nodes and E is edges:
| Operation | Cost | Why |
|---|---|---|
| Add node | One map insert | |
| Add edge | Append to one neighbor list, or two if undirected | |
| Remove edge | Must scan the neighbor list to locate it | |
| Remove node | Every 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 neighbors | The list holds precisely what you asked for | |
| Space | One 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.