Topological Sort
Topological sorting for Directed Acyclic Graph (DAG) is a linear ordering of vertices such that for every directed edge uv
, vertex u
comes before v
in the ordering.
Implementation
We represent the graph G
as unordered_map<int, vector<int>>
which is a map from source node to a list of destination nodes.
If u
must happens before v
, or in other words, v
is dependent on u
, then there is a directed edge u -> v
, where u
is the source node, and v
is the destination node.
Kahn Algorithm (BFS)
It requires additional space for storing the indegree
s of the nodes.
Put all the vertices with 0 in-degree in to a
queue q
.Get a vertex
u
at a time fromq
, and decrement the in-degree of all its neighbors.If a neighbor has 0 in-degree, add it to
q
.Keep repeating until we exhaust
q
.If the number of visited vertices equals the total number of vertices, it's a DAG; otherwise, there must be a circle in the graph.
DFS (Post-order Traversal)
A DFS version topological sort must be a Post-order DFS + Memoization.
Each vertex has three states:
-1 = unvisited
0 = being visited in the current DFS session. If we visit a node with state 0, it means there is a circle in the graph.
1 = has been visited in a prevous DFS session and this vertex is not in a circle.
It's a post-order DFS -- the node is pushed into the answer after all its subsequent nodes are visited.
Don't forget to reverse the ans
before returning.
Problems
Last updated