Graph Theory Introduction
Graph Theory: Comprehensive Study Notes
Introduction to Graph Theory
Graph theory is the study of properties and applications of graphs, which are also called networks. Graphs can represent almost any problem, making them incredibly versatile across computer science and real-world applications.
Graph – a collection of nodes (vertices) connected by edges. Representing a problem as a graph allows visualization using nodes and edges to show relationships. For example, a social network: nodes are people, edges represent friendships. Questions like "how many friends does person X have?" or "how many degrees of separation between two people?" can be answered using graph algorithms.
Types of Graphs
Undirected Graphs
Undirected graph: edges have no orientation. An edge from node u to node v is identical to the edge from v to u.
Example: cities connected by bidirectional roads – you can drive from one city to another and back.
Directed Graphs (Digraphs)
Directed graph: edges are directed (have arrowheads). An edge from u to v means you can only go from u to v, not the reverse.
Example: people who bought each other gifts – an incoming edge represents receiving a gift, an outgoing edge represents giving a gift.
Weighted Graphs
Weighted graph: edges contain weights representing cost, distance, quantity, etc. Weighted graphs can be directed or undirected.
Notation: an edge is often denoted as a triplet (u,v,w) where u is the source node, v is the destination node, and w is the weight.
Special Types of Graphs
Tree
Tree: an undirected graph with no cycles.
Equivalent definitions: a graph with n nodes and n−1 edges, or any connected acyclic graph.
Rooted Tree
Rooted tree: a tree with a designated root node. Edges either point away from the root (out-tree or arborescence) or toward the root (in-tree or anti-arborescence). Out-trees are more common.
Directed Acyclic Graph (DAG)
DAG: a directed graph with no cycles. Important for dependency structures like scheduling, build systems, compilers, and university class prerequisites.
Topological ordering: an ordering of nodes such that for every directed edge u→v, u appears before v in the ordering. This tells you how to process tasks respecting dependencies.
Bipartite Graph
Bipartite graph: vertices can be split into two independent groups U and V such that every edge connects between U and V. Equivalent to the graph being 2-colorable or having no odd-length cycles.
Common problem: maximum matching (e.g., matching people to jobs).
Complete Graph
Complete graph: a graph where there is a unique edge between every pair of nodes. Denoted Kn for n vertices. Complete graphs represent the worst-case scenario in terms of edge count.
Graph Representations
Adjacency Matrix
Adjacency matrix: a 2D matrix of size V×V where cell M[i][j] represents the edge weight from node i to node j.
Advantages:
Space-efficient for dense graphs.
O(1) edge lookup.
Simplest representation.
Disadvantages:
Requires O(V2) space – unfeasible for large graphs (e.g., 10,000+ nodes).
O(V2) work to iterate over all edges, inefficient for sparse graphs.
Adjacency List
Adjacency list: a map from each node to a list of edges (neighboring nodes and edge weights). Each node tracks its outgoing edges.
Advantages:
Great for sparse graphs – only stores existing edges.
Efficient iteration over all edges.
Disadvantages:
Less space-efficient for dense graphs.
O(E) time to access a specific edge's weight (though rarely needed).
Edge List
Edge list: an unordered list of all edges, typically represented as triplets (u,v,w).
Advantages:
Simple structure.
Good for sparse graphs.
Easy iteration.
Disadvantages:
Slow edge lookup.
Memory issues on large graphs.
Common Graph Theory Problems
Shortest Path Problem
Given a weighted graph, find the shortest path from node A to node B. Algorithms include:
Breadth-First Search (for unweighted graphs)
Dijkstra's algorithm
Bellman-Ford
A
Connectivity
Does there exist a path from node A to node B? Solutions: union-find data structure, DFS, or BFS.
Negative Cycle Detection
Negative cycle: a cycle where the sum of edge weights is negative. Can cause infinite looping in shortest path algorithms.
Applications: currency arbitrage – detecting negative cycles to find risk-free profit.
Algorithms: Bellman-Ford, Floyd-Warshall.
Strongly Connected Components (SCCs)
Strongly connected component: a self-contained cycle in a directed graph where every vertex can reach every other vertex in the same component.
Useful as an intermediate step in many algorithms.
Algorithm: Tarjan's algorithm.
Traveling Salesman Problem (TSP)
TSP: given n cities and distances between each pair, find the shortest path that visits each city exactly once and returns to the starting city.
NP-hard problem, but can be solved for small instances using dynamic programming (e.g., Held-Karp algorithm) or approximation algorithms.
Bridges and Articulation Points
Bridge: an edge whose removal increases the number of connected components. Indicates bottlenecks/vulnerabilities.
Articulation point: a node whose removal increases the number of connected components.
Applications: network reliability, finding critical connections.
Minimum Spanning Tree (MST)
MST: a subset of edges that connects all vertices without cycles and with minimal total cost.
Algorithms: Kruskal's algorithm, Prim's algorithm, Borůvka's algorithm.
Maximum Flow
Flow network: a directed graph where edge weights represent capacities (e.g., max cars on a road, water flow through pipes).
Maximum flow: the maximum amount of flow that can be pushed from a source node to a sink node, respecting capacities.
Applications: identifying bottlenecks, traffic analysis, pipe networks.
Algorithms: Ford-Fulkerson method, Edmonds-Karp, Dinic's algorithm.
Depth-First Search (DFS)
DFS is a core traversal algorithm that explores nodes and edges of a graph. It runs in O(V+E) time.
Algorithm: start at a node, mark it visited, then recursively explore unvisited neighbors. When stuck (no unvisited neighbors), backtrack.
DFS by itself is simple, but augmented variants can:
Count connected components.
Determine connectivity.
Find bridges and articulation points.
Detect cycles.
Find strongly connected components.
Topologically sort DAGs.
Generate mazes.
DFS pseudocode:
visited = [false] * n function dfs(at): if visited[at]: return visited[at] = true for each neighbor of at: dfs(neighbor)
Finding Connected Components with DFS
Use DFS on every unvisited node; each DFS call labels all nodes in one component with the same ID.
Algorithm:
count = 0, for each nodeiif not visited, run DFS, incrementcount, label nodes withcount.
Breadth-First Search (BFS)
BFS explores nodes in layers – visits all neighbors before moving to the next level. It runs in O(V+E) time.
Useful for finding the shortest path on an unweighted graph.
Uses a queue to maintain the order of visitation.
BFS pseudocode (shortest path):
function bfs(start, end): queue = new Queue() queue.enqueue(start) visited = [false] * n visited[start] = true prev = [null] * n while queue not empty: node = queue.dequeue() for neighbor in adjacency_list[node]: if not visited[neighbor]: visited[neighbor] = true prev[neighbor] = node queue.enqueue(neighbor) return reconstruct_path(prev, start, end)
Shortest Path on a Grid
Implicit graph: a grid where neighbors are determined by position (up, down, left, right). Use direction vectors (e.g.,
[-1,0], [1,0], [0,-1], [0,1]) to compute neighbors.Convert grid to adjacency list/matrix if needed, but avoid it for efficiency.
BFS on grid: start from start cell, expand to unvisited cells not blocked, count steps using layer tracking.
Direction vector technique:
dirs = { {-1,0}, {1,0}, {0,-1}, {0,1} } for each dir in dirs: rr = r + dir.r cc = c + dir.c if 0 <= rr < rows and 0 <= cc < cols and not visited[rr][cc] and grid[rr][cc] != '#': enqueue and mark visited
Topological Sort (TopSort)
Topological ordering: an ordering of nodes in a DAG such that for every directed edge u→v, u appears before v.
Only possible on DAGs. Graphs with cycles have no topological ordering.
DFS-based algorithm:
Pick an unvisited node, do DFS.
On recursive callback, push the current node to a stack (or prepend to list).
The resulting order (reversed when popping) is a topological ordering.
TopSort pseudocode (optimized):
function topsort(n, graph): visited = [false] * n ordering = [0] * n i = n - 1 for each node at in [0..n-1]: if not visited[at]: i = dfs(at, visited, ordering, i) return ordering function dfs(at, visited, ordering, i): visited[at] = true for each edge from at: if not visited[edge.to]: i = dfs(edge.to, visited, ordering, i) ordering[i] = at return i - 1
Shortest/Longest Path on DAG
Single-source shortest path on DAG can be solved in O(V+E) by topological ordering: process nodes in topological order, relax each outgoing edge.
Longest path on DAG: multiply edge weights by −1, find shortest path, then negate the answer.
Dijkstra's Shortest Path Algorithm
Dijkstra's algorithm is a single-source shortest path algorithm for graphs with non-negative edge weights. It runs in O(ElogV) with a binary heap.
Greedy: always selects the node with the smallest tentative distance.
Lazy implementation: uses a standard priority queue (duplicates okay) – O(ElogE).
Eager implementation: uses an indexed priority queue (IPQ) to avoid duplicates and allow decreased key – O(ElogV).
Optimizations:
Stop early once the destination is visited.
Use a D-ary heap for better performance on dense graphs.
Fibonacci heap gives O(E+VlogV) but high constant factors.
Lazy Dijkstra pseudocode:
function dijkstra(n, graph, start): dist = [inf] * n; dist[start] = 0 pq = min-priority queue of (dist, node) pq.enqueue((0, start)) visited = [false] * n while pq not empty: (d, u) = pq.dequeue() if visited[u]: continue visited[u] = true for each edge (u, v, w) in graph[u]: if visited[v]: continue newDist = dist[u] + w if newDist < dist[v]: dist[v] = newDist pq.enqueue((newDist, v)) return dist
Bellman-Ford Algorithm
Bellman-Ford is a single-source shortest path algorithm that works with negative edge weights and can detect negative cycles.
Time complexity: O(V⋅E).
Steps:
Initialize distance to source = 0, all others = infinity.
Relax all edges V−1 times.
Run a second pass to detect negative cycles: if any edge can still be relaxed, mark affected nodes as −∞.
Bellman-Ford pseudocode:
function bellmanFord(n, edges, start): dist = [inf] * n; dist[start] = 0 for i = 0 to n-2: for each edge (u, v, w): if dist[u] + w < dist[v]: dist[v] = dist[u] + w // detect negative cycles for i = 0 to n-2: for each edge (u, v, w): if dist[u] + w < dist[v]: dist[v] = -inf return dist
Floyd-Warshall Algorithm
Floyd-Warshall is an all-pairs shortest path algorithm. It works on graphs with any edge weights (including negative) and detects negative cycles.
Time complexity: O(V3).
Uses dynamic programming with a 2D matrix
dp[i][j](in-place update).After the algorithm,
dp[i][j]gives the shortest distance from i to j.Steps:
Initialize
dpwith adjacency matrix; set diagonal to 0, non-edges to infinity.For each intermediate node k, update all pairs (i,j):
If
dp[i][k] + dp[k][j] < dp[i][j], update.Also maintain a
nextmatrix for path reconstruction.
Detect negative cycles: if
dp[i][i] < 0, there is a negative cycle reachable from i.
Floyd-Warshall recurrence:
dp[i][j]=min(dp[i][j],dp[i][k]+dp[k][j])
Bridges and Articulation Points
Bridges (Cut Edges)
Bridge: an edge whose removal increases the number of connected components.
Algorithm (linear time using DFS):
Assign each node an
idand alowvalue (lowest id reachable via back edges).During DFS, update
lowvalues.Bridge condition: an edge u→v is a bridge if
id[u] < low[v](after exploring v).
Implementation uses a single DFS pass, updating
lowon backtrack and on viewing back edges.
Articulation Points (Cut Vertices)
Articulation point: a node whose removal increases the number of connected components.
Algorithm modifies the bridge-finding DFS:
Track number of outgoing edges from the root node of each component.
Articulation condition: if
id[u] <= low[v]and u is not the root, or if u is root and has more than one child, then u is an articulation point.
Strongly Connected Components (Tarjan's Algorithm)
Tarjan's algorithm finds all SCCs in a directed graph in O(V+E) time.
Uses DFS with a stack. Each node gets an
idandlowvalue.Key invariant: nodes on the stack are candidates for being part of an SCC. Low values are updated only from nodes on the stack.
When a node's
idequals itslow, it is the root of an SCC; pop all nodes from the stack until that node to form the SCC.
Tarjan's SCC steps:
For each unvisited node, run DFS.
Assign
idandlow= global counter; push node onto stack.For each neighbor:
If unvisited, recursively DFS; after return, update
lowfrom neighbor'slowif neighbor is on stack.If visited and on stack, update
lowwith neighbor'sid.If
id == low, pop stack until current node; all popped nodes form an SCC.
Traveling Salesman Problem (TSP) – Dynamic Programming
TSP: find the minimum cost Hamiltonian cycle in a complete graph (or with missing edges as infinity).
Time complexity: O(n22n).
DP state:
dp[mask][i]= minimum cost to start from start node, visit all nodes inmask, and end at node i.Steps:
Initialize
dpwith direct edges from start node to every other node.For increasing subset sizes, compute optimal cost.
After DP, find minimum over
dp[all][i] + cost(i, start).Reconstruct the tour by working backwards from the full mask.
Eulerian Paths and Circuits
Eulerian path: a path that visits every edge exactly once. Eulerian circuit: a path that starts and ends at the same vertex.
Existence conditions (directed and undirected) based on node degrees:
Graph Type | Eulerian Circuit | Eulerian Path |
|---|---|---|
Undirected | All vertices have even degree. | Exactly 0 or 2 vertices have odd degree. |
Directed | Every vertex has equal in-degree and out-degree. | At most one vertex has |
Algorithm (Hierholzer's) using DFS:
Find a valid start node (for circuit, any node with degree > 0; for path, the node with
out - in = 1).Perform DFS, removing edges as visited.
When stuck, backtrack and add node to path.
Final order is reversed path.
Minimum Spanning Tree (Prim's Algorithm)
Prim's algorithm finds an MST by growing a tree from a starting node, always adding the cheapest edge connecting a node in the tree to a node outside.
Lazy version: O(ElogE) – use a priority queue of edges, skip stale edges.
Eager version: O(ElogV) – use an indexed priority queue to track best incoming edge for each node.
Eager Prim's steps:
Start at any node, relax all its edges.
While IPQ not empty and MST not complete:
Extract node with cheapest incoming edge.
Add edge to MST.
Relax all edges of that node.
Network Flow
Flow Graph Definitions
Flow network: directed graph with source s, sink t, each edge has capacity (max flow) and flow.
Capacity constraint: flow ≤ capacity.
Flow conservation: for non-source/sink nodes, flow in = flow out.
Maximum flow: maximum total flow from s to t.
Ford-Fulkerson Method
Repeatedly find augmenting paths in the residual graph (includes reverse edges) and augment flow until no more paths exist.
Residual capacity: cf(u,v)=c(u,v)−f(u,v) plus the capacity of reverse edges.
Augmenting path: path from s to t with positive residual capacity on all edges.
Bottleneck: minimum residual capacity along path.
Edmonds-Karp Algorithm
Ford-Fulkerson with BFS to find shortest augmenting path (in number of edges).
Time complexity: O(VE2) – strongly polynomial, independent of capacities.
Capacity Scaling
Heuristic: prioritize edges with larger residual capacity.
Maintain a parameter Δ (largest power of two ≤ max edge capacity). While Δ>0:
Find augmenting paths using only edges with residual capacity ≥Δ.
After no more such paths, halve Δ.
Uses DFS; time O(E2logU).
Dinic's Algorithm
Dinic's algorithm is a fast maximum flow algorithm.
Level graph: obtained by BFS from s, only edges that go from level l to l+1 (forward progress) are kept.
Blocking flow: a flow augmentation phase where multiple DFS runs saturate the level graph.
Steps:
BFS to build level graph. If t not reached, stop.
DFS repeatedly from s to t using only level graph edges, pruning dead ends (using next-edge pointer).
Sum bottlenecks; when no more paths, rebuild level graph.
Time: O(V2E) on general graphs; O(VE) on bipartite graphs.
Max Flow for Bipartite Matching
Convert bipartite graph to flow network:
Source to left part (capacity 1 per node).
Left to right edges (capacity 1).
Right to sink (capacity 1, or higher if multiple copies).
Run max flow; edges with flow 1 in the middle represent the matching.
Min-Cut and Max-Flow
Max-flow min-cut theorem: the value of the maximum flow equals the capacity of the minimum s-t cut.
Additional Problem: Mice and Owls
Problem: m mice on a field, h holes with capacities, each mouse can run distance r. Find max mice that can hide.
Model as bipartite graph: mouse can reach hole if distance ≤r.
Add source to mice (capacity 1), mice to holes (capacity 1), holes to sink (capacity of hole).
Max flow gives answer.
Additional Problem: Elementary Math
Problem: given n pairs (a,b), assign each an operator (+,−,×) so that all results are distinct.
Model as bipartite matching: left side = pairs, right side = possible results. Edge if result is achievable.
Add source to pairs (capacity = frequency of pair), pairs to results (capacity 1), results to sink (capacity 1).
Max flow of n indicates solution exists.

Ask anything
We've read this whole study set, so questions about it get the best answers.