Kahn's Algorithm - Topological Sorting
Kahn's algorithm is a method used to perform a topological sort on a directed acyclic graph(DAG). A topological sort produces a linear ordering of vertices such that every directed edge from vertex u to vertex v, u comes before v in the ordering. Main applications of the algorithm are
- Course prerequisite scheduling
- Build dependency resolution
- Task scheduling with dependencies
- Detecting cycles in directed graph
- Python
from collections import defaultdict, deque
class Graph:
def kahn_topological_sort(self, edges, num_vertices):
adj = defaultdict(list)
in_degree = defaultdict(int)
nodes = set()
# Build graph and in-degree map
for u, v in edges:
adj[u].append(v)
in_degree[v] += 1
nodes.add(u)
nodes.add(v)
# Initialize in-degree for all nodes (including isolated nodes)
for i in range(num_vertices):
in_degree.setdefault(i, 0)
nodes.add(i)
# Queue all nodes with in-degree 0
queue = deque([node for node in nodes if in_degree[node] == 0])
topo_order = []
while queue:
u = queue.popleft()
topo_order.append(u)
for v in adj[u]:
in_degree[v] -= 1
if in_degree[v] == 0:
queue.append(v)
if len(topo_order) != num_vertices:
raise ValueError("Graph has a cycle, topological sort not possible.")
return topo_order