Search

Search papers and lessons

Graph

Level 1 · 9 min read

A graph is a set of vertices joined by edges, a simple way to write down anything made of things and the links between them.

On this page

TL;DR

A graph is a set of points, called vertices, and a set of connections between pairs of them, called edges. The points can stand for people, cities, web pages or variables, and the edges for friendships, roads, links or dependencies. Once a problem is written as a graph, questions like "can I get from here to there?" or "what is the shortest route?" become questions about edges.

Graphs are the most general way to write down relationships. A table of rows has no links between rows, but a graph records which items connect to which.

Where you'll see it: in social networks and road maps, in the dependency order of software builds, and in graph neural networks, where each node's features are updated from its neighbours.

Intuition

Dots and lines

Draw five dots on a page and join some of them with lines. That picture is a graph. The dots are vertices and the lines are edges. Nothing about the layout matters: you can move the dots anywhere and drag the lines around, and it is still the same graph as long as the same pairs are joined. What the graph records is only who is connected to whom.

This is why graphs are so useful. Many real systems have an obvious structure of parts and links, but the geometry is irrelevant. A map of an airline's routes is a graph of airports, not a picture of the countries. The question "can I fly from A to B with at most two connections?" depends only on the links, so the graph is all you need.

Where the idea came from

The idea was born from a puzzle. In the town of Königsberg, seven bridges crossed the river Pregel and joined two islands to the banks. Was there a walk that crossed each bridge exactly once? Leonhard Euler realised that the land areas and the bridges could be replaced by points and lines. Only the connections mattered, not the distances. He showed in 1736 that no such walk exists, and that reasoning began graph theory.

flowchart LR
  A((A)) --- B((B))
  A --- C((C))
  B --- C
  C --- D((D))
  B --- D

The diagram above is a graph with four vertices AA, BB, CC, DD and five edges. It is the same graph whatever positions the circles are drawn at.

The math

Definition

Definition: Graph

A graph is a pair G=(V,E)G = (V, E), where VV is a finite set of vertices and EE is a set of edges. In an undirected graph, each edge is an unordered pair {u,v}\{u, v\} of distinct vertices u,v∈Vu, v \in V.

Here VV is a set of labels, and EE is another set whose members are pairs of labels. The notation {u,v}\{u, v\} means the pair without an order, so {u,v}\{u, v\} and {v,u}\{v, u\} are the same edge. We say uu and vv are adjacent when {u,v}∈E\{u, v\} \in E, and that the edge joins them.

For the diagram above, V={A,B,C,D}V = \{A, B, C, D\} and E={{A,B},{A,C},{B,C},{C,D},{B,D}}E = \{\{A,B\}, \{A,C\}, \{B,C\}, \{C,D\}, \{B,D\}\}.

Directed and weighted graphs

Two common variants change one thing each.

  • In a directed graph, each edge is an ordered pair (u,v)(u, v), drawn with an arrow from uu to vv. A one-way street or a link from one web page to another is directed.
  • In a weighted graph, each edge carries a number, the weight w(u,v)w(u, v). A road might carry its length, and a recommendation might carry a score.

Degree

The degree of a vertex vv, written deg⁡(v)\deg(v), is the number of edges that touch it. In the example, deg⁡(A)=2\deg(A) = 2, deg⁡(B)=3\deg(B) = 3, deg⁡(C)=3\deg(C) = 3 and deg⁡(D)=2\deg(D) = 2.

Each edge has two ends, so counting ends over all vertices counts every edge twice:

∑v∈Vdeg⁡(v)=2 ∣E∣.\sum_{v \in V} \deg(v) = 2\,|E|.

This is the handshake lemma. Here it says 2+3+3+2=10=2×52 + 3 + 3 + 2 = 10 = 2 \times 5. Any graph has an even number of odd-degree vertices as a consequence.

Paths and connectivity

A path from uu to vv is a sequence of vertices u=v0,v1,…,vk=vu = v_0, v_1, \dots, v_k = v in which each consecutive pair is joined by an edge. Its length is kk, the number of edges used. A graph is connected when there is a path between every pair of its vertices. The graph in the diagram is connected: from AA you can reach DD by A,C,DA, C, D, which has length 2.

A cycle is a path that starts and ends at the same vertex without repeating any other vertex, with at least three vertices. The triangle A,B,CA, B, C is a cycle.

A useful consequence

A connected graph with nn vertices needs at least n−1n - 1 edges, and a graph with exactly n−1n - 1 edges that is connected has no cycles. Such a graph is called a tree. Trees are the simplest connected graphs, and they show up as family trees, file systems and the structure a search algorithm builds as it explores.

Worked examples

Example
Counting edges in a friendship network

Five people, Ana, Ben, Cara, Dev and Eli, have these friendships: Ana–Ben, Ana–Cara, Ben–Cara, Cara–Dev and Dev–Eli.

  1. Vertices: V={Ana,Ben,Cara,Dev,Eli}V = \{\text{Ana}, \text{Ben}, \text{Cara}, \text{Dev}, \text{Eli}\}, so ∣V∣=5|V| = 5.
  2. Edges: ∣E∣=5|E| = 5, one per friendship.
  3. Degrees: Ana 2 (Ben, Cara), Ben 2 (Ana, Cara), Cara 3 (Ana, Ben, Dev), Dev 2 (Cara, Eli), Eli 1 (Dev). The sum is 2+2+3+2+1=102 + 2 + 3 + 2 + 1 = 10.
  4. Check: 2 ∣E∣=2×5=102\,|E| = 2 \times 5 = 10, which matches the degree sum.
  5. Path from Ana to Eli: Ana, Cara, Dev, Eli, of length 3.

Interpretation: Cara is the most connected person, so she is the best person to pass a message through. If Cara leaves the group, Eli is cut off from Ana and Ben. The degree of a vertex, and the edges that a path must pass through, tell you that without drawing anything.

Example
Is there a walk over every bridge?

Euler's puzzle, in graph form. The city has four land areas, so four vertices. Seven bridges give seven edges. The degrees are: each land area's degree equals the number of bridges touching it. One area has degree 5 and three have degree 3, so the degrees sum to 5+3+3+3=14=2×75 + 3 + 3 + 3 = 14 = 2 \times 7.

  1. Count the odd-degree vertices: all four are odd (5, 3, 3, 3).
  2. A walk that uses every edge exactly once (an Eulerian trail) can have at most two odd-degree vertices, since it starts at one and ends at another and every other vertex is entered and left in pairs.
  3. Here there are four odd-degree vertices, which is more than two.

So no such walk exists. Notice that the calculation never needed the bridge lengths or the shape of the land. It needed only the degrees of the vertices.

Tradeoffs and failure modes

To use a graph in a program you must store it, and there are two standard ways. Each suits different questions.

SituationProblem with the other choiceBetter representation
Many vertices, few edges (a road map, a social network)An adjacency matrix wastes space on the empty entriesAdjacency list: for each vertex, store its neighbours
Need to check instantly whether two vertices are joinedScanning a neighbour list takes time[[adjacency-matrix
Dense graph, nearly every pair joinedA list costs about as much as a matrix and is slower to indexAdjacency matrix
Want linear algebra on the structure (spectral methods, graph neural networks)A list does not support matrix operationsAdjacency matrix, often with a normalised form

Other failure modes are conceptual. A graph hides the geometry on purpose, so it cannot tell you that two nearby cities are far apart by road. Edges that hold a weight need a weighted graph, and an unweighted shortest-path algorithm will give the wrong answer on them. Real networks can be very large, and some questions that look easy on a small drawing (such as finding the best route through every vertex) are known to be hard in general.

History

Euler's 1736 paper on the Seven Bridges of Königsberg is usually taken as the start of graph theory. For about a century the subject stayed a set of puzzles. Gustav Kirchhoff used trees and cycles in the 1840s to analyse electrical circuits, and Arthur Cayley counted trees in the 1850s, motivated by the chemical structure of hydrocarbons. Dénes Kőnig collected the results in the first textbook on the subject in 1936. The field grew after the 1950s, when computers made it practical to run algorithms on graphs, and it became central to computer science: networks, databases, compilers and search. In machine learning, graphs returned in the 2010s with graph neural networks, which pass information along edges.

Check yourself

QuestionA graph has 6 vertices and every vertex has degree 3. How many edges does it have?Show answer

The degree sum is 6×3=186 \times 3 = 18. By the handshake lemma, ∑deg⁡(v)=2∣E∣\sum \deg(v) = 2|E|, so ∣E∣=18/2=9|E| = 18 / 2 = 9.

QuestionCompute the degree of each vertex in a graph with edges {A,B}\{A,B\}, {B,C}\{B,C\}, {C,A}\{C,A\} and {C,D}\{C,D\}. Which vertex has the largest degree?Show answer

deg⁡(A)=2\deg(A) = 2 (joined to BB and CC), deg⁡(B)=2\deg(B) = 2 (joined to AA and CC), deg⁡(C)=3\deg(C) = 3 (joined to AA, BB and DD), and deg⁡(D)=1\deg(D) = 1. Vertex CC has the largest degree, 3. The degrees sum to 2+2+3+1=8=2×42+2+3+1 = 8 = 2 \times 4, which matches four edges.

QuestionWhy does a tree on nn vertices have exactly n−1n - 1 edges?Show answer

A tree is connected and has no cycles. Start with one vertex and add the others one at a time, each joined to the tree by a single edge. Joining a new vertex by two edges would create a cycle, and joining it by none would leave it disconnected. So each of the n−1n - 1 vertices after the first contributes exactly one edge.

QuestionYou store a road network of 2 million junctions where each junction has about 4 roads. Which representation should you use for finding each junction's neighbours, and why?Show answer

An adjacency list. An adjacency matrix would need 2,000,0002=4×10122{,}000{,}000^2 = 4 \times 10^{12} entries, almost all zero. The list stores only the roughly 8 million directed neighbour entries, and reading the roads out of a junction takes time proportional to its degree, which is about 4.

Sources