-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathall-topological-ordering-of-given-dag.py
51 lines (40 loc) · 1.4 KB
/
all-topological-ordering-of-given-dag.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
from collections import deque
"""Given a directed acyclic graph (DAG) with n vertices and m edges,
find all possible topological orderings of the vertices.
"""
class Graph:
def __init__(self, edges, N) -> None:
self.V = N
self.adjList = [[] for _ in range(N)]
self.indegree = [0] * N
for (src, dest) in edges:
self.adjList[src].append(dest)
self.indegree[dest] += 1
def findAllTopologicalorderings(self, discovered, path):
for v in range(self.V):
if self.indegree[v] == 0 and not discovered[v]:
for u in self.adjList[v]:
self.indegree[u] -= 1
path.append(v)
discovered[v] = True
self.findAllTopologicalorderings(discovered, path)
for u in self.adjList[v]:
self.indegree[u] += 1
path.pop()
discovered[v] = False
if len(path) == self.V:
print(path)
def printAllTopologicalOrders(self):
"""
>>> N = 4
>>> edges = [(0,1),(1,2),(2,3)]
>>> graph = Graph(edges,N)
>>> graph.printAllTopologicalOrders()
[0, 1, 2, 3]
"""
discovered = [False] * self.V
path = []
self.findAllTopologicalorderings(discovered, path)
if __name__ == "__main__":
import doctest
doctest.testmod(verbose=True)