-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy path127_topological_sorting.py
More file actions
37 lines (32 loc) · 952 Bytes
/
127_topological_sorting.py
File metadata and controls
37 lines (32 loc) · 952 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
36
37
"""
Definition for a Directed graph node
class DirectedGraphNode:
def __init__(self, x):
self.label = x
self.neighbors = []
"""
class Solution:
"""
@param: graph: A list of Directed graph node
@return: Any topological order for the given graph.
"""
def topSort(self, graph):
ans = []
if not graph:
return ans
indegs = {}
for node in graph:
if node not in indegs:
indegs[node] = 0
for _node in node.neighbors:
if _node not in indegs:
indegs[_node] = 0
indegs[_node] += 1
queue = [node for node, indeg in indegs.items() if indeg == 0]
for node in queue:
ans.append(node)
for _node in node.neighbors:
indegs[_node] -= 1
if indegs[_node] == 0:
queue.append(_node)
return ans