1:The topological sort algorithm takes a directed graph and returns an array of the nodes where each node appears before all the nodes it points to.
The ordering of the nodes in the array is called a topological ordering.
Well, let’s focus on the first node in the topological ordering. That node can’t have any incoming directed edges; it must have an indegree ↴ of zero. Then follow below algorithm.
This is a common algorithm design pattern:
- Figure out how to get the first thing.
- Remove the first thing from the problem.
- Repeat.
Implementation
We’ll use the strategy we outlined above:
- Identify a node with no incoming edges.
- Add that node to the ordering.
- Remove it from the graph.
- Repeat.