Topological Sort
Topological sort helps in scheduling job, resolving dependencies order and identifying dead locks. It can be done using both DFS and BFS
For topological sort to be done, the graph should be Directed Acyclic Graph (DAG), i.e. no cycles should be found in the graph.
Topological sort can help us identify if the graph is DAG or not. If the end result size is not equal to total number of courses, then there exists a cycle in given graph.

DFS
BFS (Khan's Algorithm)
Kahn's algorithm is a topological sorting algorithm that works by repeatedly adding vertices with an indegree of 0 to a queue. Once all of the vertices have been added to the queue, the algorithm removes them from the queue in the order that they were added. This gives us a topological order of the graph.
Indegree
Indegree is the number of edges that are directed into a vertex. A vertex with an indegree of 0 is a vertex that has no incoming edges.
The significance of the indegree is to determine the number of prerequisites or dependencies for each course or node in a directed graph.
Significance of indegree
By identifying the nodes with an indegree of 0, we can find the nodes that have no prerequisites or dependencies. These nodes can be processed first since they do not rely on any other nodes.
By enqueuing the nodes with an indegree of 0, the algorithm begins by handling the nodes that have no dependencies, gradually progressing towards the nodes with higher indegrees.
Significance of decrementing the in degree
By decrementing the indegree of a node, we indicate that one of its dependencies has been fulfilled or processed.
Decrementing the indegree helps keep track of the remaining prerequisites for each node.
When the indegree of a node becomes 0, it means that all its prerequisites have been satisfied, and the node becomes eligible for processing.
Nodes with an indegree of 0 are enqueued and processed first since they have no dependencies or prerequisites.
The process continues, gradually processing nodes with higher indegrees as their prerequisites are fulfilled.
Decrementing the indegree ensures that nodes are processed in the correct order based on their prerequisites, leading to a valid topological ordering.
Code
Last updated