Graph Theory
The mathematics of networks — vertices, edges, degree and the handshake lemma, paths, cycles and connectivity, trees and their properties, bipartite graphs, Euler and Hamiltonian paths, planar graphs, graph colouring, matchings, and the many problems that reduce to graphs.
A graph G = (V, E) is a set of vertices (nodes) and edges connecting pairs of them. Graphs model social networks, road maps, the web, dependencies between packages, state machines, circuits, molecules and more. This lesson covers the theory; for data structures and algorithms see Graphs, Graph traversal and Shortest paths.
Vocabulary
| Term | Meaning |
|---|---|
| Directed / undirected | Edges have a direction (follows, links) or not (friendship, roads) |
| Weighted | Edges carry costs (distance, latency, capacity) |
| Degree | Number of edges at a vertex; directed graphs have in-degree and out-degree |
| Path | A sequence of vertices connected by edges; simple if no repeated vertices |
| Cycle | A path that returns to its start |
| Connected | A path exists between every pair of vertices (undirected) |
| Strongly connected | A directed path exists both ways between every pair |
| DAG | Directed acyclic graph — dependencies, build systems, schedules |
| Complete graph | Every pair connected: edges |
| Sparse / dense | E close to V, or close to V² |
| Subgraph | A subset of vertices and edges |
The handshake lemma
In any undirected graph, the sum of degrees is twice the number of edges (each edge contributes to two vertices):
A corollary: the number of vertices with odd degree is always even. (At a party, the number of people who shook an odd number of hands is even.)
Connectivity
- Connected components partition an undirected graph (an equivalence relation — Sets and relations); find them with BFS/DFS or union–find.
- Strongly connected components of a directed graph collapse into a DAG (the condensation) — Tarjan's or Kosaraju's algorithm (Topological sort and SCC).
- A bridge is an edge whose removal disconnects the graph; an articulation point is such a vertex — single points of failure in a network.
- Menger's theorem: the minimum number of edges whose removal disconnects s from t equals the maximum number of edge-disjoint s–t paths — the max-flow min-cut idea (Network flow).
Trees
A tree is a connected graph with no cycles. For a graph with n vertices, these are equivalent:
- It is a tree (connected and acyclic).
- It is connected and has exactly n − 1 edges.
- It is acyclic and has exactly n − 1 edges.
- There is exactly one simple path between any two vertices.
- Removing any edge disconnects it; adding any edge creates exactly one cycle.
A spanning tree connects all vertices of a graph using a subset of its edges; a minimum spanning tree does so with least total weight (Minimum spanning trees). Cayley's formula: the complete graph has spanning trees. A forest is a disjoint union of trees.
Rooted trees give the familiar parent/child/leaf/depth vocabulary of trees in data structures.
Bipartite graphs
A graph is bipartite if its vertices can be split into two sets with every edge going between them: users and products, jobs and workers, students and courses.
Theorem: a graph is bipartite if and only if it has no odd-length cycle. Test it by 2-colouring with BFS: colour the start red, its neighbours blue, and so on; a conflict means an odd cycle.
from collections import deque
def is_bipartite(adj):
color = {}
for start in adj:
if start in color: continue
color[start] = 0
q = deque([start])
while q:
u = q.popleft()
for v in adj[u]:
if v not in color:
color[v] = 1 - color[u]
q.append(v)
elif color[v] == color[u]:
return False # odd cycle
return TrueMatchings pair vertices along edges with no vertex used twice. Maximum bipartite matching (assigning workers to jobs, students to projects) is solvable in polynomial time with augmenting paths (Hopcroft–Karp) or max flow. Hall's theorem says when a perfect matching of one side exists: every subset S of that side must have at least neighbours.
Euler and Hamiltonian paths
The Königsberg bridges problem (Euler, 1736) founded graph theory: can you walk across each of the city's seven bridges exactly once?
| Eulerian path/circuit | Hamiltonian path/cycle | |
|---|---|---|
| Visits each | Edge exactly once | Vertex exactly once |
| Exists when | Circuit: connected and every vertex has even degree. Path: exactly 0 or 2 odd-degree vertices | No simple characterisation |
| Complexity | Easy — O(E) with Hierholzer's algorithm | NP-complete to decide |
| Applications | Route inspection (snowplough, mail delivery), DNA fragment assembly (de Bruijn graphs), reconstructing an itinerary | Travelling salesman, scheduling |
Königsberg had four land masses all with odd degree — so no such walk exists. Two problems that sound almost identical land on opposite sides of the P vs NP divide (Complexity classes).
Planar graphs
A graph is planar if it can be drawn in the plane without edges crossing (circuit boards, maps). Euler's formula for connected planar graphs:
where F counts faces (including the outer one). Consequences: a simple planar graph has at most 3V − 6 edges, so planar graphs are sparse. and ("three houses, three utilities") are not planar — and by Kuratowski's theorem, every non-planar graph contains a subdivision of one of them.
Graph colouring
Assign colours to vertices so that adjacent vertices differ. The minimum number of colours is the chromatic number χ(G).
| Application | Vertices | Edges | Colours |
|---|---|---|---|
| Register allocation | Variables | Live at the same time | CPU registers (Code generation) |
| Exam scheduling | Exams | Share a student | Time slots |
| Frequency assignment | Radio towers | Would interfere | Frequencies |
| Map colouring | Regions | Share a border | Colours |
| Sudoku | Cells | Same row/column/box | Digits 1–9 |
- Deciding whether χ(G) ≤ 3 is NP-complete; in practice, greedy heuristics work well.
- Bipartite graphs are exactly the 2-colourable graphs.
- Four colour theorem (1976, the first major computer-assisted proof): every planar map can be coloured with four colours.
Special graphs and properties
- Small-world networks: most nodes are reachable in a few hops ("six degrees of separation") — social networks, the web.
- Scale-free networks: degree follows a power law — a few hubs with huge degree (celebrity accounts, popular sites); robust to random failures, fragile to targeted attacks on hubs; hot partitions in systems design.
- Expander graphs: sparse yet highly connected — used in network design and error-correcting codes.
- Random graphs (Erdős–Rényi): a giant connected component appears suddenly once the average degree exceeds 1 — a phase transition.
Thinking in graphs
Many problems become easy once modelled as graphs:
| Problem | Graph model |
|---|---|
| Word ladder (cold → warm) | Words as vertices, one-letter changes as edges → BFS |
| Course schedule feasibility | Prerequisites as directed edges → cycle detection / topological sort |
| Currency arbitrage | Exchange rates as edges with weight −log(rate) → negative cycle (Bellman–Ford) |
| Network reliability | Bridges and articulation points |
| Recommendations | Bipartite user–item graph; random walks |
| Deadlock detection | Wait-for graph cycles (Deadlocks) |
- Graphs model relationships: directed or undirected, weighted or not; degree, paths, cycles, connectivity.
- Handshake lemma: degrees sum to 2|E|; the number of odd-degree vertices is even.
- Trees are connected, acyclic graphs with n − 1 edges and unique paths between vertices.
- A graph is bipartite iff it has no odd cycle; bipartite matching is efficiently solvable.
- Euler paths (each edge once) are easy via degree parity; Hamiltonian paths (each vertex once) are NP-complete.
- Planar graphs satisfy V − E + F = 2; graph colouring models register allocation and scheduling.