![]() |
VOOZH | about |
Kahn's Algorithm is used for topological sorting of a directed acyclic graph (DAG). The algorithm works by repeatedly removing nodes with no incoming edges and recording them in a topological order. Here's a step-by-step implementation of Kahn's Algorithm in Python.
Example:
Input: V=6 , E = {{2, 3}, {3, 1}, {4, 0}, {4, 1}, {5, 0}, {5, 2}}
👁 ImageOutput: 5 4 2 3 1 0
Explanation: In the above output, each dependent vertex is printed after the vertices it depends upon.Input: V=5 , E={{0, 1}, {1, 2}, {3, 2}, {3, 4}}
👁 ImageOutput: 0 3 4 1 2
Explanation: In the above output, each dependent vertex is printed after the vertices it depends upon.
We'll represent the graph using an adjacency list. Additionally, we need to keep track of the in-degree (number of incoming edges) of each node.
The algorithm uses a queue to manage nodes with no incoming edges.
Now we can combine the graph creation and Kahn's Algorithm into a complete example.
Here is the complete code for Kahn's Algorithm in Python:
Topological Order: [4, 5, 2, 0, 3, 1]
Time Complexity: O(N)
Auxiliary Space: O(N)