Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit ed6e2a4

Browse files
committed
2 parents d870ea0 + eaded9d commit ed6e2a4

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

algorithms/topological_sort.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
def topological_sort(graph):
2+
from collections import deque
3+
indeg = [0] * len(graph)
4+
result = []
5+
q = deque()
6+
for ns in graph:
7+
for n in ns:
8+
indeg[n] += 1
9+
10+
for i in range(len(graph)):
11+
if indeg[i] == 0:
12+
q.appendleft(i)
13+
14+
while q:
15+
n = q.pop()
16+
result.append(n)
17+
for i in graph[n]:
18+
indeg[i] -= 1
19+
if indeg[i] == 0:
20+
q.appendleft(i)
21+
return result
22+

0 commit comments

Comments
 (0)