Today, I read an article about the ideas and applications of topological sorting, and I manually implemented it.
Data structure
Algorithms are built on concrete data structures. For this problem, let’s first look at how to abstract the problem background into concrete data structures.
We can abstract the dependency relationship between source files and source files into a directed graph. Each source file corresponds to a vertex in the graph, and the dependency relationship between source files is the edge between the vertices.
If a executes before b, that is, b depends on a, then between vertices a and b, build an edge from a to b. Moreover, this graph must not only be a directed graph, but also a Directed Acyclic Graph, that is, there cannot be a circular dependency like a- > b- > c- > a. Because once a ring appears in the graph, topological sorting cannot work. In fact, topological sorting itself is an algorithm based on Directed Acyclic Graph.