-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTopological-Sort.py
More file actions
35 lines (28 loc) · 957 Bytes
/
Copy pathTopological-Sort.py
File metadata and controls
35 lines (28 loc) · 957 Bytes
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
#push the elements which have indegree=0
#perform bfs algo (pop q[0] and reduce the indegree of it's adjacent nodes by 1
#check if there is any node with indegree = 0,
#if no: move ahead and pop another element and repeat,
#if yes, insert that node into queue )
class Solution:
#Function to return list containing vertices in Topological order.
def topoSort(self, V, adj):
ans = []
indegree = [0]*V
for i in range(V):
for j in adj[i]:
indegree[j] = indegree[j]+1
q = []
for i in range(V):
if indegree[i]==0:
q.append(i)
while(q):
node = q.pop(0)
ans.append(node)
for i in adj[node]:
indegree[i] = indegree[i]-1
if indegree[i]==0:
q.append(i)
return ans
#TC = O(N+E)
#SC = O(N)+O(N)
#QUEUE AND INDEGREE ARRAY