Chapter 22: Elementary Graph Algorithms

December 12, 2020

Thomas H. Cormen, Charles E. Leiserson, Ronald Rivest, Clifford Stein. Introduction to Algorithms, Second Edition. The MIT Press, 2001

The basics of encoding and traversing graphs.

22.1 Representation of Graphs

Introduction to Algorithms defines graphs as G=(V,E),wG=(V,E), w, where V|V| is the number of vertices in the graph, E|E| is the number of edges in the graph, and w(u,v),{u,v}Ew(u,v), \{u, v\} \subseteq E is a function that defines the weight of edges.

O(VE)O(|V||E|) will be written as O(VE)O(VE).

The source of a graph traversal is often noted as ss.

A sparse graph is a graph where E|E| is much smaller than V|V|.

Adjacency List:

  • An array, AdjAdj, of length V|V| such that Adj[u]=[Adj[u]=[all vertices adjacent to uu in G]G]
  • Uses Θ(V+E)\Theta(V+E) memory.
  • Takes O(V)O(V) time to check if an edge (u,v)(u,v) exists.

Adjacency Matrix:

  • A matrix A=(aij)A=(a_{ij}) of size V|V|xV|V| such that aij={1if (i,j)ϵE0otherwisea_{ij} = \begin{cases} 1 & \text{if } (i,j) \epsilon E\\ 0 & \text{otherwise} \end{cases}
  • Uses O(V2)O(V^2) memory. For undirected graphs, the adjacency matrix is symmetrical along its diagonal so slightly less than half of it can be ignored without losing information.
  • Takes O(1)O(1) time to check if an edge (u,v)(u,v) exists.

22.2 Breadth-First Search

  • Uses a queue in the iterative version
  • Takes O(V+E)O(V+E) time to run

22.3 Depth-First Search

  • Uses a queue in the iterative version
  • Takes O(V+E)O(V+E) time to run

22.4 Topological Sort

A DAG is a directed acyclic graph.

A topological sort of a dag G=(V,E)G=(V,E) is a linear ordering of all its vertices such that if GG contains an edge (u,v)(u,v), then uu appears before vv in the ordering.

Introduction to Algorithms Second Edition, page 549
TOPOLOGICAL-SORT(GG)
  1. call DFS(GG) to compute finishing times f[v]f[v] for each vertex vv
  2. as each vertex is finished, insert it onto the front of a linked list
  3. return the linked list of vertices
Introduction to Algorithms Second Edition, page 550

22.5 Strongly Connected Components

A strongly connected component of a directed graph G=(V,E)G=(V,E) is a maximal set of vertices CVC \subseteq V such that for every pair of vertices uu and vv in CC, we have both uvu \leadsto v and vuv \leadsto u; that is, vertices uu and vv are reachable from each other.

Introduction to Algorithms Second Edition, page 552
STRONGLY-CONNECTED-COMPONENTS(GG)
  1. call DFS(GG) to compute finishing times f[u]f[u] for each vertex uu
  2. compute GTG^T
  3. call DFS(GTG^T), but in the main loop of DFS, consider the vertices in order of decreasing f[u]f[u] (as computed in line 1)
  4. ouput the vertices of each tree in the depth-first forest formed in line 3 as a separate strongly connected component
Introduction to Algorithms Second Edition, page 554