Topological Sorting¶
You are given a directed graph with
In other words, you want to find a permutation of the vertices (topological order) which corresponds to the order defined by all edges of the graph.
Here is one given graph together with its topological order:


Topological order can be non-unique (for example, if there exist three vertices

A Topological order may not exist at all.
It only exists, if the directed graph contains no cycles.
Otherwise, there is a contradiction: if there is a cycle containing the vertices
A common problem in which topological sorting occurs is the following. There are
The Algorithm¶
To solve this problem, we will use depth-first search.
Let's assume that the graph is acyclic. What does the depth-first search do?
When starting from some vertex
Thus, by the time of the function call
Let's append the vertex
These explanations can also be presented in terms of exit times of the DFS algorithm.
The exit time for vertex
Implementation¶
Here is an implementation which assumes that the graph is acyclic, i.e. the desired topological ordering exists. If necessary, you can easily check that the graph is acyclic, as described in the article on depth-first search.
int n; // number of vertices
vector<vector<int>> adj; // adjacency list of graph
vector<bool> visited;
vector<int> ans;
void dfs(int v) {
visited[v] = true;
for (int u : adj[v]) {
if (!visited[u]) {
dfs(u);
}
}
ans.push_back(v);
}
void topological_sort() {
visited.assign(n, false);
ans.clear();
for (int i = 0; i < n; ++i) {
if (!visited[i]) {
dfs(i);
}
}
reverse(ans.begin(), ans.end());
}
The main function of the solution is topological_sort
, which initializes DFS variables, launches DFS and receives the answer in the vector ans
. It is worth noting that when the graph is not acyclic, topological_sort
result would still be somewhat meaningful in a sense that if a vertex
Practice Problems¶
- SPOJ TOPOSORT - Topological Sorting [difficulty: easy]
- UVA 10305 - Ordering Tasks [difficulty: easy]
- UVA 124 - Following Orders [difficulty: easy]
- UVA 200 - Rare Order [difficulty: easy]
- Codeforces 510C - Fox and Names [difficulty: easy]
- SPOJ RPLA - Answer the boss!
- CSES - Course Schedule
- CSES - Longest Flight Route
- CSES - Game Routes