Kahn’s Topological Sort

Kahn's algorithm is a popular method for topological sorting of a directed acyclic graph (DAG). Topological sorting arranges the vertices of a DAG into a linear order such that for every directed edge u→vu \rightarrow vu→v, vertex uuu comes before vvv in the ordering.

ALGORITHM

Initialize: Compute the in-degree of each vertex (number of incoming edges).

Find Start Vertices: Identify vertices with in-degree zero and add them to a queue.

Topological Sort: While the queue is not empty, remove a vertex uuu from the queue, add it to the result list, and decrement the in-degree of its neighbors. If a neighbor's in-degree becomes zero, add it to the queue.

Repeat: Repeat step 3 until all vertices are processed.

Key Points

USE CASES

Python

from collections import defaultdict

def topological_sort(graph):
    # Initialize a dictionary to store indegrees of all vertices
    indegree = defaultdict(int)
    # Initialize a list to store the sorted elements
    result = []

    # Calculate the indegrees of all vertices
    for u in graph:
        for v in graph[u]:
            indegree[v] += 1

    # Initialize a queue for Kahn's algorithm
    queue = []

    # Add all vertices with indegree 0 to the queue
    for u in graph:
        if indegree[u] == 0:
            queue.append(u)

    # Kahn's algorithm
    while queue:
        u = queue.pop(0)
        result.append(u)
        for v in graph[u]:
            indegree[v] -= 1
            if indegree[v] == 0:
                queue.append(v)

    # Check for cycles
    if len(result) != len(graph):
        raise ValueError("The graph has a cycle!")

    return result