1. Home
  2. Explore
  3. Computer Science
  4. Graph Theory Introduction

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

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 uuu to node vvv is identical to the edge from vvv to uuu.

  • 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 uuu to vvv means you can only go from uuu to vvv, 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)(u, v, w)(u,v,w) where uuu is the source node, vvv is the destination node, and www is the weight.


Special Types of Graphs

Tree

  • Tree: an undirected graph with no cycles.

  • Equivalent definitions: a graph with nnn nodes and n−1n-1n−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→vu \to vu→v, uuu appears before vvv in the ordering. This tells you how to process tasks respecting dependencies.

Bipartite Graph

  • Bipartite graph: vertices can be split into two independent groups UUU and VVV such that every edge connects between UUU and VVV. 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 KnK_nKn​ for nnn 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×VV \times VV×V where cell M[i][j]M[i][j]M[i][j] represents the edge weight from node iii to node jjj.

  • Advantages:

    • Space-efficient for dense graphs.

    • O(1)O(1)O(1) edge lookup.

    • Simplest representation.

  • Disadvantages:

    • Requires O(V2)O(V^2)O(V2) space – unfeasible for large graphs (e.g., 10,000+ nodes).

    • O(V2)O(V^2)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)O(E)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)(u, v, w)(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 AAA to node BBB. Algorithms include:

  • Breadth-First Search (for unweighted graphs)

  • Dijkstra's algorithm

  • Bellman-Ford

  • A

Connectivity

Does there exist a path from node AAA to node BBB? 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 nnn 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)O(V + E)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 node i if not visited, run DFS, increment count, label nodes with count.


Breadth-First Search (BFS)

BFS explores nodes in layers – visits all neighbors before moving to the next level. It runs in O(V+E)O(V + E)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→vu \to vu→v, uuu appears before vvv.

  • Only possible on DAGs. Graphs with cycles have no topological ordering.

  • DFS-based algorithm:

    1. Pick an unvisited node, do DFS.

    2. On recursive callback, push the current node to a stack (or prepend to list).

    3. 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)O(V+E)O(V+E) by topological ordering: process nodes in topological order, relax each outgoing edge.

  • Longest path on DAG: multiply edge weights by −1-1−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(Elog⁡V)O(E \log V)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(Elog⁡E)O(E \log E)O(ElogE).

  • Eager implementation: uses an indexed priority queue (IPQ) to avoid duplicates and allow decreased key – O(Elog⁡V)O(E \log V)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+Vlog⁡V)O(E + V \log V)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)O(V \cdot E)O(V⋅E).

  • Steps:

    1. Initialize distance to source = 0, all others = infinity.

    2. Relax all edges V−1V-1V−1 times.

    3. Run a second pass to detect negative cycles: if any edge can still be relaxed, mark affected nodes as −∞-\infty−∞.

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)O(V^3)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 iii to jjj.

  • Steps:

    1. Initialize dp with adjacency matrix; set diagonal to 0, non-edges to infinity.

    2. For each intermediate node kkk, update all pairs (i,j)(i, j)(i,j):

      • If dp[i][k] + dp[k][j] < dp[i][j], update.

      • Also maintain a next matrix for path reconstruction.

    3. Detect negative cycles: if dp[i][i] < 0, there is a negative cycle reachable from iii.

Floyd-Warshall recurrence:

dp[i][j]=min⁡(dp[i][j],dp[i][k]+dp[k][j])dp[i][j] = \min(dp[i][j], dp[i][k] + dp[k][j])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 id and a low value (lowest id reachable via back edges).

    • During DFS, update low values.

    • Bridge condition: an edge u→vu \to vu→v is a bridge if id[u] < low[v] (after exploring vvv).

  • Implementation uses a single DFS pass, updating low on 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 uuu is not the root, or if uuu is root and has more than one child, then uuu is an articulation point.


Strongly Connected Components (Tarjan's Algorithm)

Tarjan's algorithm finds all SCCs in a directed graph in O(V+E)O(V+E)O(V+E) time.

  • Uses DFS with a stack. Each node gets an id and low value.

  • 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 id equals its low, it is the root of an SCC; pop all nodes from the stack until that node to form the SCC.

Tarjan's SCC steps:

  1. For each unvisited node, run DFS.

  2. Assign id and low = global counter; push node onto stack.

  3. For each neighbor:

    • If unvisited, recursively DFS; after return, update low from neighbor's low if neighbor is on stack.

    • If visited and on stack, update low with neighbor's id.

  4. 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)O(n^2 2^n)O(n22n).

  • DP state: dp[mask][i] = minimum cost to start from start node, visit all nodes in mask, and end at node iii.

  • Steps:

    1. Initialize dp with direct edges from start node to every other node.

    2. For increasing subset sizes, compute optimal cost.

    3. After DP, find minimum over dp[all][i] + cost(i, start).

    4. 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 out - in = 1, at most one has in - out = 1, all others equal.

  • Algorithm (Hierholzer's) using DFS:

    1. Find a valid start node (for circuit, any node with degree > 0; for path, the node with out - in = 1).

    2. Perform DFS, removing edges as visited.

    3. When stuck, backtrack and add node to path.

    4. 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(Elog⁡E)O(E \log E)O(ElogE) – use a priority queue of edges, skip stale edges.

  • Eager version: O(Elog⁡V)O(E \log V)O(ElogV) – use an indexed priority queue to track best incoming edge for each node.

Eager Prim's steps:

  1. Start at any node, relax all its edges.

  2. 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 sss, sink ttt, each edge has capacity (max flow) and flow.

  • Capacity constraint: flow ≤\le≤ capacity.

  • Flow conservation: for non-source/sink nodes, flow in = flow out.

  • Maximum flow: maximum total flow from sss to ttt.

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)c_f(u,v) = c(u,v) - f(u,v)cf​(u,v)=c(u,v)−f(u,v) plus the capacity of reverse edges.

  • Augmenting path: path from sss to ttt 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)O(V E^2)O(VE2) – strongly polynomial, independent of capacities.

Capacity Scaling

  • Heuristic: prioritize edges with larger residual capacity.

  • Maintain a parameter Δ\DeltaΔ (largest power of two ≤\le≤ max edge capacity). While Δ>0\Delta > 0Δ>0:

    • Find augmenting paths using only edges with residual capacity ≥Δ\ge \Delta≥Δ.

    • After no more such paths, halve Δ\DeltaΔ.

  • Uses DFS; time O(E2log⁡U)O(E^2 \log U)O(E2logU).

Dinic's Algorithm

Dinic's algorithm is a fast maximum flow algorithm.

  • Level graph: obtained by BFS from sss, only edges that go from level lll to l+1l+1l+1 (forward progress) are kept.

  • Blocking flow: a flow augmentation phase where multiple DFS runs saturate the level graph.

  • Steps:

    1. BFS to build level graph. If ttt not reached, stop.

    2. DFS repeatedly from sss to ttt using only level graph edges, pruning dead ends (using next-edge pointer).

    3. Sum bottlenecks; when no more paths, rebuild level graph.

  • Time: O(V2E)O(V^2 E)O(V2E) on general graphs; O(VE)O(\sqrt{V} E)O(V​E) 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 sss-ttt cut.


Additional Problem: Mice and Owls

  • Problem: mmm mice on a field, hhh holes with capacities, each mouse can run distance rrr. Find max mice that can hide.

  • Model as bipartite graph: mouse can reach hole if distance ≤r\le r≤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 nnn pairs (a,b)(a,b)(a,b), assign each an operator (+,−,×+, -, \times+,−,×) 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 nnn indicates solution exists.

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent