Given an directed graph, a topological order of the graph nodes is defined as follow:
For each directed edge A -> B in graph, A must before B in the order list.
The first node in the order can be any node in the graph with no nodes direct to it.
Find any topological order for the given graph
Notice
You can assume that there is at least one topological order in the graph.
# Definition for a Directed graph node# class DirectedGraphNode:# def __init__(self, x):# self.label = x# self.neighbors = []classSolution:deftopSort(self,graph):indegree={}ret=[]queue=[]# indegree <graphnode, degree> forxingraph:indegree[x]=0# count indegreeforiingraph:forjini.neighbors:indegree[j]=indegree[j]+1# find the starerforiingraph:ifindegree[i]==0:ret.append(i)queue.append(i)# bfs: use queue (use bfs in my code)# dfs: use recursivewhilelen(queue)!=0:cur=queue[0]queue.pop(0)foriincur.neighbors:indegree[i]-=1ifindegree[i]==0:ret.append(i)queue.append(i)returnret