Using BFS for topological sort
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.
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.
Related reading
- Using BFS for Weighted Graphs
- Using circular permutations to reduce Traveling Salesman complexity
- Using Dijkstra's algorithm to find a path that can carry the most weight
- Using os.walk to recursively traverse directories in Python
- Using kubectl set image to update image of initContainer
- Using LINQ to remove elements from a ListT
- Using Paxos in dynamic environment
- Using Queues to uniformly sample from multiple input files

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.