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.

Intermediate 6 min readLesson 5 of 9

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

TermMeaning
Directed / undirectedEdges have a direction (follows, links) or not (friendship, roads)
WeightedEdges carry costs (distance, latency, capacity)
DegreeNumber of edges at a vertex; directed graphs have in-degree and out-degree
PathA sequence of vertices connected by edges; simple if no repeated vertices
CycleA path that returns to its start
ConnectedA path exists between every pair of vertices (undirected)
Strongly connectedA directed path exists both ways between every pair
DAGDirected acyclic graph — dependencies, build systems, schedules
Complete graph KnK_nEvery pair connected: (n2)\binom{n}{2} edges
Sparse / denseE close to V, or close to V²
SubgraphA subset of vertices and edges
ABCDE
Undirected graph: deg(C) = 3; A–B–C forms a cycle; D–E hangs off C

The handshake lemma

In any undirected graph, the sum of degrees is twice the number of edges (each edge contributes to two vertices):

∑v∈Vdeg⁡(v)=2∣E∣\sum_{v \in V} \deg(v) = 2\lvert E \rvert

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:

  1. It is a tree (connected and acyclic).
  2. It is connected and has exactly n − 1 edges.
  3. It is acyclic and has exactly n − 1 edges.
  4. There is exactly one simple path between any two vertices.
  5. 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 KnK_n has nn−2n^{n-2} 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.

Python
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 True

Matchings 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 ∣S∣\lvert S \rvert 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/circuitHamiltonian path/cycle
Visits eachEdge exactly onceVertex exactly once
Exists whenCircuit: connected and every vertex has even degree. Path: exactly 0 or 2 odd-degree verticesNo simple characterisation
ComplexityEasy — O(E) with Hierholzer's algorithmNP-complete to decide
ApplicationsRoute inspection (snowplough, mail delivery), DNA fragment assembly (de Bruijn graphs), reconstructing an itineraryTravelling 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:

V−E+F=2V - E + F = 2

where F counts faces (including the outer one). Consequences: a simple planar graph has at most 3V − 6 edges, so planar graphs are sparse. K5K_5 and K3,3K_{3,3} ("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).

ApplicationVerticesEdgesColours
Register allocationVariablesLive at the same timeCPU registers (Code generation)
Exam schedulingExamsShare a studentTime slots
Frequency assignmentRadio towersWould interfereFrequencies
Map colouringRegionsShare a borderColours
SudokuCellsSame row/column/boxDigits 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:

ProblemGraph model
Word ladder (cold → warm)Words as vertices, one-letter changes as edges → BFS
Course schedule feasibilityPrerequisites as directed edges → cycle detection / topological sort
Currency arbitrageExchange rates as edges with weight −log(rate) → negative cycle (Bellman–Ford)
Network reliabilityBridges and articulation points
RecommendationsBipartite user–item graph; random walks
Deadlock detectionWait-for graph cycles (Deadlocks)
Key takeaways
  • 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.