Topological sorting is a sort of Directed Acyclic graphs, which meets the following two conditions:
1. Each vertex appears only once;
2. If A is ranked before B in the sequence, there is no path from B to A in the figure.
In the above undirected directed graph, v indicates vertices: v = ['A', 'B', 'C', 'D', 'E'], and e Indicates directed edges: e = [('A', 'B'), ('A', 'D'), ('B', 'C'), ('D ', 'C'), ('D', 'E'), ('E', 'C')], the Code is as follows:
Def indegree0 (v, e): if v = []: return Nonetmp = v [:] for I in e: if I [1] in tmp: tmp. remove (I [1]) if tmp = []: return-1for t in tmp: for I in range (len (e): if t in e [I]: e [I] = 'todel '# placeholder, and then delete if e: eset = set (e) eset. remove ('todel ') e [:] = list (eset) if v: for t in tmp: v. remove (t) return tmpdef topoSort (v, e): result = [] while True: nodes = indegree0 (v, e) if nodes = None: breakif nodes =-1: print ('There \'s a circle. ') return Noneresult. extend (nodes) return resultv = ['A', 'B', 'C', 'D', 'E'] e = [('A ', 'B'), ('A', 'D'), ('B', 'C'), ('D ', 'E'), ('E', 'C')] res = topoSort (v, e) print (res)
The indegree0 function returns the vertex with an inbound value of 0 and deletes its adjacent edge in v and e. If no vertex exists in the v list, None is returned, if there are still vertices in the v list but the vertex with an inbound degree of 0 cannot be found, it indicates that the directed graph has a ring and-1 is returned. The topoSort function constantly extracts the vertex with an inbound degree of 0 from the directed graph, and finally the topological sorting sequence. The output is as follows:
['a', 'b', 'd', 'e', 'c']
Consider a case where a ring exists and add a side c-> d, as shown in:
The output is as follows:
there's a circle.None
Reprinted Please note: