Topological Sort
Photo by Martin Martz
Topological Sort is a linear ordering of vertices such that for every directed edge u->v, vertex u comes before v in the ordering.
Let's illustrate a simplified problem within a build system scenario, which is a common application of Topological Sorting.
Imagine you are working on a software project with multiple modules. Some modules depend on others to be built first. You are required to find a build order that will allow all modules to be built without any dependency errors.
Here's a representation of the modules and dependencies:
- Module depends on Module and Module
- Module depends on Module and Module
- Module depends on Module
- Module has no dependencies
This scenario can be represented by a directed graph. In this graph, an edge from Module to Module means must be built before , as depends on .
- Vertices (Modules):
- Let represent the set of vertices, where each vertex is a module.
- Edges (Dependencies):
- Let represent the set of directed edges, where each edge is a dependency. An edge from vertex to vertex (denoted as ) implies that module depends on module .
- Adjacency List Representation:
- Given the input, the adjacency list can be represented as follows:
- - Module A depends on modules B and C.
- - Module B depends on modules C and D.
- - Module C depends on module D.
- - Module D has no dependencies.
- Given the input, the adjacency list can be represented as follows:
- Graph Notation:
- The graph can be denoted as where:
- Where is the set of vertices (modules) and is the set of directed edges (dependencies). The direction of an edge indicates the direction of dependency. For instance, the edge implies that module A is dependent on module B.
- The graph can be denoted as where:
- Reverse Graph Construction:
- Construct a reverse graph where contains edges in the opposite direction of .
- For each dependency in the original graph , add an edge to .
- If then .
- Indegree Calculation:
- For each vertex in , calculate the indegree, , representing the number of incoming edges in .
- .
- Queue Initialization:
- Initialize a queue with all vertices where .
- Topological Sorting Using Queue:
- Initialize an empty list .
- While is not empty:
- Dequeue vertex from .
- Add to .
- For each vertex where (in the reverse graph):
- Decrement by 1.
- If , enqueue into .
- Cycle Detection and Order Validation:
- If the length of is not equal to the number of vertices , it implies that a cycle exists in the graph or not all nodes are connected, making topological sorting impossible.