classGraph:def __init__(self): self. V= []classVertex:def __init__(self, x): Self.key=x Self.color=' White'SELF.D= 10000SELF.F= 10000Self.pi=None Self.adj=[] Self.next=NoneclassSolution:defDfs (Self, G): forUinchG.v:u.color=' White'U.pi=NoneGlobal Time Time=0 forUinchG.V:ifU.color = =' White': Self. Dfsvisit (G, u)defdfsvisit (self, G, u):Global Time Time= time + 1U.D=Time U.color='Gray' forVinchU.adj:ifV.color = =' White': Self. Dfsvisit (G, v) v.pi=u u.color='Black' Time= time + 1U.F= TimedefTopologicalsort (Self, G): LinkedList= Vertex ('#') self. Dfs (G) g.v.sort (Key=Lambdav:v.f) forVinchG.v:v.next=Linkedlist.next Linkedlist.next=vreturnLinkedListif __name__=='__main__': Undershorts= Vertex ('Undershorts') Socks= Vertex ('Socks') Pants= Vertex ('Pants') Shoes= Vertex ('Shoes') Belt= Vertex ('Belt') Shirt= Vertex ('Shirt') Tie= Vertex ('Tie') Jacket= Vertex ('Jacket') Watch= Vertex ('Watch') Undershorts.adj=[pants, shoes] Socks.adj=[shoes] Pants.adj=[belt, shoes] Shoes.adj=[] Belt.adj=[jacket] Shirt.adj=[Belt, tie] Tie.adj=[jacket] Jacket.adj=[] Watch.adj=[] G=Graph () g.v=[Undershorts,socks,pants,shoes,belt,shirt,tie,jacket,watch] m=solution () sort_list=m.topologicalsort (G) p=sort_list whileP.next! =None:PrintP.next.key, P.next.f p= P.next
[Introduction to Algorithms] topological ordering @ Python