Understanding the Problem
Topological Sort is used to linearly order the vertices of a Directed Acyclic Graph (DAG) such that for every directed edge u → v
, vertex u
comes before v
in the order. This is often used in scheduling problems, like task execution order based on dependencies.
We will solve this using Kahn’s Algorithm, which uses a Breadth-First Search (BFS) approach based on indegree counts.
Step-by-Step Solution with Example
Step 1: Represent the Graph
We represent the graph using an adjacency list and also track the indegree (number of incoming edges) for each node.
Example: Given edges: [[5, 0], [4, 0], [5, 2], [2, 3], [3, 1], [4, 1]]
This means:
- 5 → 0
- 4 → 0
- 5 → 2
- 2 → 3
- 3 → 1
- 4 → 1
Step 2: Compute Indegrees
We loop over all edges and count how many edges point to each vertex.
After processing the above edges, indegrees would look like:
0: 2
1: 2
2: 1
3: 1
4: 0
5: 0
Step 3: Initialize Queue
We add all vertices with indegree 0 to a queue. These are the starting points because they have no dependencies.
Queue: [4, 5]
Step 4: BFS Traversal
While the queue is not empty:
- Dequeue a node and add it to the result.
- For each of its neighbors, reduce their indegree by 1.
- If a neighbor’s indegree becomes 0, add it to the queue.
Progress:
Queue: [4, 5] → [5, 0] → [0, 2] → [2, 3] → [3, 1] → [1]
Result: [4, 5, 0, 2, 3, 1]
Step 5: Check for Cycles
If at the end, the result does not contain all nodes, it means a cycle exists and topological sort is not possible. If the size of the result equals the number of vertices, we have a valid topological order.
Edge Cases
Case 1: Empty Graph
If the graph has no vertices, return an empty list. No work to be done.
Case 2: Single Node with No Edges
The output is simply the node itself.
Case 3: Multiple Starting Nodes
When multiple nodes have indegree 0, the result may vary depending on which is dequeued first. All are valid topological orders.
Case 4: Cycle in Graph
If there's a cycle, like 1 → 2 → 3 → 1
, no topological sort is possible. Our result will have fewer nodes than expected, indicating a cycle.
Finally
Kahn’s Algorithm is a simple yet powerful way to solve topological sorting using a queue and indegree tracking. It not only provides the topological order but also helps in detecting cycles in the graph. This is especially useful in real-life applications like course prerequisites, task scheduling, and build systems.
Comments
Loading comments...