# Kahn's Algorithm

A topological sort is a graph traversal where each node is visited only after all its dependencies have first been visited.

Topological sorting is used where things need to be scheduled based on their dependencies. For example, course schedules. A student needs to take CS101 before they can take CS201, and they need to take CS201 before they can take CS301. Other areas of applications are build programs in CS (a program's dependencies need to be built in a certain order), event scheduling, assembly instructions etc.

There can be more than one valid topological sort. In the following graph the following topological sorts are possible:

- A B C D
- A C B D
- A C D B

Directed Acyclic Graph

A topological sort is only possible on a directed acyclic graph (DAG). This is because if the graph contained a cycle, then a sort order cannot be found. For example, in the following graph, C depends on A and B. But B depends on D which depends on C. C depends on a dependency (D) which depends on C! So, it is invalid.

A graph which contains a cycle. A topological sort is not possible

Kahn's Alogorithm finds a topological sort of a DAG. It works by repeatedly removing vertices that have no incoming edges. Those removed vertices are recorded to the topological sort set/array.

In the above DAG graph, vertex A is the only vertex with no incoming edges. It is the starting point for the algorithm. It is removed and put in the topological sort set. Now, B and C vertices have no incoming edges. One is picked arbitrarily to process. Say B. B is removed to the topolgoical sort set. Now C is the only vertice without any incoming edges. C is removed. And finally D. The topological sort in this example is A, B, C, D.

The code below is a simple implementation of Kahn's algorithm. It assumes the vertices value are integers in the range of 0...number of vertices. This allows for an array to track the number of incoming edges for each vertex.

1

'''

2

Kahn's algorithm - used for finding a topological sort (ordering) of a directed acyclic graph.

3

'''

4

from typing import List

5

from collections import defaultdict, deque

6

7

8

class Graph:

9

10

__MIN_VALUE__ = 0

11

12

def __init__(self, num_vertices):

13

self.graph = defaultdict(list)

14

self.num_vertices = num_vertices

15

16

def __is_valid__(self, num: int) -> bool:

17

return num >= Graph.__MIN_VALUE__ and num < self.num_vertices

18

19

def add_edge(self, u: int, v: int):

20

'''

21

Add an edge from vertex u to vertex v

22

'''

23

if not self.__is_valid__(u) or not self.__is_valid__(v):

24

raise Exception(f"Invalid vertex value. Must be between {Graph.__MIN_VALUE__} and {self.num_vertices}")

25

self.graph[u].append(v)

26

27

def add_non_connected_vertex(self, u):

28

self.graph[u].append(None)

29

30

31

32

class Kahns:

33

def kahn(self, graph: Graph) -> List[int]:

34

# this array keeps track of how many edges are incoming to a vertex (how many dependecies a course has)

35

# because the vertices ints an array can be used. The array index is the vertex int

36

incoming_edges = [0] * graph.num_vertices

37

38

# populate the incoming_edges with the number of incoming edges for each vertex

39

for u in graph.graph:

40

for v in graph.graph[u]:

41

if v:

42

incoming_edges[v] += 1

43

44

45

# initialize the queue with any vertices that do NOT have any incoming edges (0 dependencies)

46

processing_queue = deque()

47

for vertex, edges in enumerate(incoming_edges):

48

if edges == 0:

49

processing_queue.append(vertex)

50

51

52

topo_sort = []

53

num_vertices_processed = 0

54

while processing_queue:

55

vertex = processing_queue.pop()

56

num_vertices_processed += 1

57

topo_sort.append(vertex)

58

for v in graph.graph[vertex]:

59

if v:

60

incoming_edges[v] -= 1

61

if incoming_edges[v] == 0:

62

processing_queue.append(v)

63

64

# The graph contains a cycle if these two values do not match

65

if num_vertices_processed != graph.num_vertices:

66

raise Exception("Invalid graph")

67

return topo_sort

68

Last modified 6mo ago