# 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: A list of graph nodes in topological order.
"""
def topSort(self, graph):
# write your code her
from collections import deque
result = []
map = {}
q = deque()
# build a hash table to count the indegrees
for node in graph:
for n in node.neighbors:
if n in map :
map[n] += 1
else:
map[n] = 1
# add the first indegree is 0 to the queue, no indegree is the first node
for node in graph:
if node not in map:
q.append(node)
result.append(node)
# if the current indegree is 0 mean it's current node.
while len(q) > 0:
node = q.popleft()
for n in node.neighbors:
map[n] -= 1
if map[n] == 0:
result.append(n)
q.append(n)
return result