Using BFS for topological sort
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
In computer science, topological sorting is a crucial concept used primarily with directed acyclic graphs (DAGs). It provides a linear order of vertices such that for every directed edge `uv` from vertex `u` to vertex `v`, `u` appears before `v` in the ordering. One popular algorithm to achieve this is using Breadth-First Search (BFS), specifically utilizing a variant known as Kahn's Algorithm.
Understanding BFS for Topological Sort
Topological sorting via BFS involves the computation of in-degrees of all vertices in the graph. An in-degree of a node is the number of edges directed towards it. Using these in-degrees, we repeatedly perform a BFS-like traversal to derive the sorted order.
Steps of the Algorithm
- Calculate In-Degrees: Traverse the graph to compute the in-degree for each vertex.
- Initialize the Queue: Create a queue and enqueue all vertices with in-degree `0` since they have no dependencies that must precede them.
- Process the Queue:
- Dequeue a vertex `u` from the queue.
- Append `u` to the topological ordering.
- For each adjacent vertex `v` of `u`, decrease the in-degree of `v` by `1`.
- If the in-degree of `v` becomes zero, enqueue `v`.
- Verify the Result: If the number of vertices in the topological order is less than the number of vertices in the graph, the graph has at least one cycle and cannot be sorted topologically.
Example
Consider the following directed graph:
5 -> 0 -> 4 2 3 1 6
- Step 1: Calculate In-Degrees:
- `indegree[5] = 0`, `indegree[0] = 1`, `indegree[4] = 1`, `indegree[2] = 1`
- `indegree[3] = 1`, `indegree[1] = 1`, `indegree[6] = 1`
- Step 2: Initialize the Queue: Enqueue `5`.
- Step 3: Process:
- `indegree[0] = 0`, `indegree[2] = 0`
- `indegree[3] = 0`
- `indegree[1] = 0`, `indegree[6] = 0`
- Final Order: `[5, 0, 2, 3, 1, 6]` (Note: there are multiple valid topological sorts)
- Complexity: The algorithm runs in `O(V + E)` time, where `V` is the number of vertices and `E` is the number of edges, as it processes each vertex and edge once.
- DAG Requirement: The graph must be a DAG; otherwise, a cycle will prevent a valid ordering.
- Indegree as an Indicator: The use of in-degree is pivotal as it indicates the readiness of a vertex to appear in the ordering.
- Dependency Resolution: Used in build systems like `make`, `ant`, and others to resolve dependencies between tasks or components.
- Course Scheduling: In academic planning, courses with prerequisites can be lined up using topological sort.
- Pathfinding: Helps in resolving order of tasks in scheduling problems, especially when constraints are represented as a DAG.

