TExcelTAD
Home › Graph Algorithms › Graph Algorithms: What This Course Covers

Graph Algorithms: What This Course Covers

A road map, a network of computers, the dependencies between the tasks of a build, the friendships in a social network, the pixels of an image: all of them are graphs, a set of things and a set of connections between pairs of them. Once a problem is phrased as a graph, a small toolbox of algorithms answers a surprising number of questions about it. Which places can be reached? What is the shortest route? In which order can the tasks run? Which cables connect every office most cheaply? How much traffic can the network carry? This course builds that toolbox and proves that every tool works.

The Data Structures and Algorithms course introduces graphs, traversals, Dijkstra, Bellman-Ford, spanning trees and Ford-Fulkerson by example, and Discrete Mathematics covers the graph theory: directed graphs, DAGs and scheduling, trees and connectivity. Here every algorithm gets pseudocode, a proof of correctness, a running-time bound and a program that counts its work.

Notation

A graph is a pair G=(V,E)G = (V, E) of a finite set of vertices VV and a set of edges EE. In a directed graph an edge is an ordered pair (u,v)(u, v), drawn as an arrow from uu to vv; in an undirected graph it is an unordered pair, written (u,v)(u, v) or {u,v}\{u, v\} for the same edge. Unless a lesson says otherwise, graphs have no self-loops and no parallel edges.

  • Size. Inside asymptotic notation, VV and EE stand for the sizes ∣V∣\lvert V \rvert and ∣E∣\lvert E \rvert, so O(V+E)O(V + E) means O(∣V∣+∣E∣)O(\lvert V \rvert + \lvert E \rvert). A sparse graph has EE close to VV, a dense one has EE close to V2V^2.
  • Degree. In an undirected graph the degree of vv is the number of edges at vv. In a directed graph vv has an out-degree (edges leaving) and an in-degree (edges entering).
  • Paths. A path is a sequence of vertices ⟨v0,v1,…,vk⟩\langle v_0, v_1, \ldots, v_k \rangle with an edge from each to the next; its length is the number of edges, kk. It is simple if no vertex repeats. A cycle is a path of length at least 1 (at least 3 in an undirected graph) whose first and last vertices are equal.
  • Weights. A weighted graph has a function w:E→Rw : E \to \mathbb{R}, and the weight of a path is the sum of the weights of its edges.

The program stores a small undirected graph as a dictionary from each vertex to its neighbours and checks the handshake lemma: every edge contributes 1 to the degree of each of its two ends, so the degrees add up to 2E2E. For the directed version both in-degrees and out-degrees add up to EE.

python · try it yourself
edges = [("A", "B"), ("A", "C"), ("B", "C"), ("B", "D"), ("C", "E"), ("D", "E"), ("D", "F"), ("E", "F")]
und = {v: [] for v in "ABCDEF"}
for u, v in edges:
    und[u].append(v)
    und[v].append(u)
deg = {v: len(nb) for v, nb in und.items()}
print("undirected degrees:", deg)
print("sum of degrees =", sum(deg.values()), "= 2 * E =", 2 * len(edges))

out_deg = {v: 0 for v in "ABCDEF"}
in_deg = {v: 0 for v in "ABCDEF"}
for u, v in edges:                     # read each pair as an arrow u -> v
    out_deg[u] += 1
    in_deg[v] += 1
print("out-degrees:", out_deg)
print("in-degrees: ", in_deg)
print("sums:", sum(out_deg.values()), sum(in_deg.values()), "= E =", len(edges))
undirected degrees: {'A': 2, 'B': 3, 'C': 3, 'D': 3, 'E': 3, 'F': 2}
sum of degrees = 16 = 2 * E = 16
out-degrees: {'A': 2, 'B': 2, 'C': 1, 'D': 2, 'E': 1, 'F': 0}
in-degrees:  {'A': 0, 'B': 1, 'C': 2, 'D': 1, 'E': 2, 'F': 2}
sums: 8 8 = E = 8

Why clever algorithms matter here

Most graph questions are about paths, and a graph can have astronomically many of them. The program builds a "ladder" of kk rungs: two rails of kk vertices each, with an edge across at every rung. It counts the simple paths from one corner to the opposite corner by trying them all, and compares that with the work of a breadth-first search, which finds the shortest of those paths by looking at each edge twice.

python · try it yourself
def ladder(k):
    adj = {(r, i): [] for r in range(2) for i in range(k)}
    def link(a, b):
        adj[a].append(b); adj[b].append(a)
    for i in range(k):
        link((0, i), (1, i))                            # rung
        if i + 1 < k:
            link((0, i), (0, i + 1)); link((1, i), (1, i + 1))   # rails
    return adj

def count_simple_paths(adj, s, t):
    calls = 0
    def go(u, seen):
        nonlocal calls
        calls += 1
        if u == t:
            return 1
        return sum(go(v, seen | {v}) for v in adj[u] if v not in seen)
    return go(s, {s}), calls

def bfs_work(adj, s):
    dist, queue, looks = {s: 0}, [s], 0
    for u in queue:
        for v in adj[u]:
            looks += 1
            if v not in dist:
                dist[v] = dist[u] + 1
                queue.append(v)
    return dist, looks

print(f"{'k':>3} {'V':>4} {'E':>4} {'simple paths':>13} {'calls to try them':>18} {'BFS edge looks':>15}")
for k in [2, 4, 6, 8, 10, 12]:
    adj = ladder(k)
    s, t = (0, 0), (1, k - 1)
    paths, calls = count_simple_paths(adj, s, t)
    dist, looks = bfs_work(adj, s)
    E = sum(len(nb) for nb in adj.values()) // 2
    print(f"{k:>3} {len(adj):>4} {E:>4} {paths:>13} {calls:>18} {looks:>15}   shortest = {dist[t]} edges")
  k    V    E  simple paths  calls to try them  BFS edge looks
  2    4    4             2                  5               8   shortest = 2 edges
  4    8   10             8                 30              20   shortest = 4 edges
  6   12   16            32                136              32   shortest = 6 edges
  8   16   22           128                566              44   shortest = 8 edges
 10   20   28           512               2292              56   shortest = 10 edges
 12   24   34          2048               9202              68   shortest = 12 edges

The number of simple paths doubles with every extra rung (2k−12^{k-1} of them for kk rungs), so trying them all is exponential, while breadth-first search does exactly 2E2E edge looks. Every algorithm in this course has the same flavour: it exploits structure (shortest paths are made of shortest paths, a cut must be crossed, a finished vertex never needs another visit) to avoid enumerating paths, trees or flows one by one.

What the course covers

Section Algorithms Main results
Representations and search adjacency lists and matrices, BFS, DFS, topological sort, Kahn, Kosaraju, Tarjan BFS computes shortest-path distances in O(V+E)O(V + E); DFS timestamps nest like parentheses; a directed graph is acyclic exactly when DFS finds no back edge; SCCs in O(V+E)O(V + E)
Minimum spanning trees the generic method, Kruskal, Prim a light edge crossing a cut that respects the current edges is safe; O(Elg⁡V)O(E \lg V) with union-find or a binary heap
Single-source shortest paths relaxation, Bellman-Ford, DAG shortest paths, Dijkstra, difference constraints Bellman-Ford handles negative weights in O(VE)O(VE) and detects negative cycles; DAGs in O(V+E)O(V + E); Dijkstra in O((V+E)lg⁡V)O((V + E) \lg V) with a binary heap
All-pairs shortest paths repeated squaring, Floyd-Warshall, transitive closure, Johnson Θ(V3)\Theta(V^3) with Floyd-Warshall; O(VElg⁡V)O(VE \lg V) for sparse graphs with Johnson's reweighting
Maximum flow Ford-Fulkerson, Edmonds-Karp, bipartite matching, push-relabel max flow equals min cut; O(VE2)O(VE^2) with shortest augmenting paths; matching as a flow problem

The Design Techniques course supplies two ideas used throughout: optimal substructure (a shortest path is made of shortest paths) and the greedy-choice property (the cut property of spanning trees is one). Two data structures from earlier courses do much of the work: the binary-heap priority queue inside Dijkstra and Prim, and union-find inside Kruskal.

Conventions

  • Arrays are 0-based, lg⁡n=log⁡2n\lg n = \log_2 n, and pseudocode follows How to read pseudocode. Graph pseudocode writes G.VG.V for the vertex set, G.Adj[u]G.\textit{Adj}[u] for the neighbours of uu, and attributes on vertices such as v.dv.d (a distance) and v.πv.\pi (the predecessor).
  • Vertices are named with letters, and neighbours are visited in alphabetical order. The step-through animations do the same, so every program prints the same steps as the animation next to it.
  • Costs are counted, never timed: edge looks, relaxations, heap operations, augmentations. Random graphs use a fixed seed, so you get exactly the output shown.
  • Every algorithm lesson has a Python version and a C++20 version under "In C++" that prints the same result. The C++ versions use only the standard library: std::vector adjacency lists, std::queue, and std::priority_queue.

The practice area has problems for many lessons, among them Shortest Paths with Negative Edges, All-Pairs Shortest Paths, Strongly Connected Components, Maximum Flow, Maximum Bipartite Matching, Shortest Distances and Course Schedule Order.

Test yourself

An undirected graph has 7 vertices whose degrees are 3, 3, 2, 2, 2, 1 and 1. How many edges does it have?

  1. 14
  2. 7
  3. 6
  4. It cannot exist

What does O(V+E)O(V + E) mean in this course?

  1. O(∣V∣+∣E∣)O(\lvert V \rvert + \lvert E \rvert), linear in the size of the graph
  2. O(∣V∣⋅∣E∣)O(\lvert V \rvert \cdot \lvert E \rvert)
  3. Time proportional to the number of paths
  4. Constant time per vertex, ignoring edges

Why do graph algorithms avoid enumerating all paths?

  1. Paths cannot be represented in memory
  2. The number of simple paths can grow exponentially with the size of the graph
  3. Only directed graphs have paths
  4. Enumeration gives wrong answers