topological sort python

Solutions on MaxInterview for topological sort python by the best coders in the world

showing results for - "topological sort python"
Gianluca
30 Aug 2016
1from collections import defaultdict
2
3class Graph:
4
5    def __init__(self,n):
6
7        self.graph = defaultdict(list)
8
9        self.N = n
10
11    def addEdge(self,m,n):
12
13        self.graph[m].append(n)
14
15    def sortUtil(self,n,visited,stack):
16
17        visited[n] = True
18
19        for element in self.graph[n]:
20
21            if visited[element] == False:
22
23                self.sortUtil(element,visited,stack)
24
25        stack.insert(0,n)
26
27    def topologicalSort(self):
28
29        visited = [False]*self.N
30
31        stack =[]
32
33        for element in range(self.N):
34
35            if visited[element] == False:
36
37                self.sortUtil(element,visited,stack)
38
39        print(stack)
40
41graph = Graph(5)
42graph.addEdge(0,1);
43graph.addEdge(0,3);
44graph.addEdge(1,2);
45graph.addEdge(2,3);
46graph.addEdge(2,4);
47graph.addEdge(3,4);
48
49print("The Topological Sort Of The Graph Is:  ")
50
51graph.topologicalSort()
52