题目:https://www.lintcode.com/problem/topological-sorting/description
思路:拓扑排序
1.统计所有点的入度
2.将入度为0的加入队列
3.bfs
"""
Definition for a Directed graph node
class DirectedGraphNode:
def __init__(self, x):
self.label = x
self.neighbors = [] # 存的是DirectedGraphNode
# len(graph) 得到node的个数
"""
class Solution:
"""
@param: graph: A list of Directed graph node
@return: Any topological order for the given graph.
"""
def topSort(self, graph):
# write your code here
if graph == None :
return []
indegree = self.indegreehelper(graph)
queue = []
for i in range(len(graph)):
if indegree[i][0] == 0:
queue.append(graph[i])
result = []
hashtable = set()
while queue :
current = queue.pop(0)
result.append(current)
for i in indegree[current.label][1]:
indegree[i.label][0] -= 1
if indegree[i.label][0] == 0:
queue.append(graph[i.label])
return result
def indegreehelper(self,graph):
indegree = [[0,[]] for x in range(len(graph))]
print indegree
for i in range(len(graph)):
for j in graph[i].neighbors:
indegree[j.label][0] += 1
indegree[i][1] = graph[i].neighbors
return indegree