Chapter 22: Elementary Graph Algorithms
December 12, 2020Thomas 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 , where is the number of vertices in the graph, is the number of edges in the graph, and is a function that defines the weight of edges.
will be written as .
The source of a graph traversal is often noted as .
A sparse graph is a graph where is much smaller than .
Adjacency List:
- An array, , of length such that all vertices adjacent to in
- Uses memory.
- Takes time to check if an edge exists.
Adjacency Matrix:
- A matrix of size x such that
- Uses 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 time to check if an edge exists.
22.2 Breadth-First Search
- Uses a queue in the iterative version
- Takes time to run
22.3 Depth-First Search
- Uses a queue in the iterative version
- Takes time to run
22.4 Topological Sort
A DAG is a directed acyclic graph.
A topological sort of a dag is a linear ordering of all its vertices such that if contains an edge , then appears before in the ordering.
TOPOLOGICAL-SORT()
- call DFS() to compute finishing times for each vertex
- as each vertex is finished, insert it onto the front of a linked list
- return the linked list of vertices
22.5 Strongly Connected Components
A strongly connected component of a directed graph is a maximal set of vertices such that for every pair of vertices and in , we have both and ; that is, vertices and are reachable from each other.
STRONGLY-CONNECTED-COMPONENTS()
- call DFS() to compute finishing times for each vertex
- compute
- call DFS(), but in the main loop of DFS, consider the vertices in order of decreasing (as computed in line 1)
- ouput the vertices of each tree in the depth-first forest formed in line 3 as a separate strongly connected component