CmSc 250 Intro to Algorithms
Graph Algorithms - Topological Sort
Topological sort: an ordering of the vertices in a directed acyclic graph, such that:
If there is a path from u to v, then v appears after u in the ordering.
Types of graphs:
The graphs should be directed: otherwise for any edge
(u,v)
there would be a path from u to v
and also from v to u,
and hence they cannot be ordered.
The graphs should be acyclic: otherwise for any two vertices
u and v on a cycle
u would precede v and v would precede u.
The ordering may not be unique:
V1, V2, V3, V4 and V1, V3, V2, V4 are legal orderings
Degree of a vertex U: the number of edges (U,V) - outgoing
edges
Indegree of a vertex U: the number of edges (V,U) -
incoming edges
The algorithm for topological sort uses "indegrees" of vertices.
If there is no such vertex then there is a cycle
and the
vertices cannot be ordered. Stop.
V1: 0
V2: 1
V3: 2
V4: 2
V5: 2
Sorted: V1
Remove edges: (V1,V2) , (V1, V3) and (V1,V4)
Updated indegrees:
V2: 0
V3: 1
V4: 1
V5: 2
The process is depicted in the following table:
|
|
Indegree |
|
|
|
|
|
|
Sorted à |
|
V1 |
V1,V2 |
V1,V2,V4 |
V1,V2,V4,V3 |
V1,V2,V4,V3,V5 |
|
V1 |
0 |
|
|
|
|
|
|
V2 |
1 |
0 |
|
|
|
|
|
V3 |
2 |
1 |
1 |
0 |
|
|
|
V4 |
2 |
1 |
0 |
|
|
|
|
V5 |
2 |
2 |
1 |
0 |
0 |
|
One possible sorting: V1, V2, V4, V3, V5
Another sorting: V1, V2, V4, V5, V3
Complexity of this algorithm: O(|V|2), |V| - the number of vertices.
To find a vertex of indegree 0 we scan all the vertices - |V| operations.
We do this for all vertices: |V|2
After the initial scanning to find a vertex of degree 0, we need to scan only those vertices whose updated indegrees have become equal to zero.
The number of operations is O(|E| + |V|), where |V| - number of
vertices, |E| - number of edges.
How many operations are needed to compute the indegrees?
Depends on the representation:
Adjacency lists: O(|E|)
Matrix: O(|V|2)
Note that if the graph is complete |E| = O(|V|2)
Learning Goals
Exam-like questions