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= []classSolution:defDfs (Self, G): forUinchG.v:u.color=' White'U.pi=NoneGlobal Time Time=0 forUinchG.V:ifU.color = =' White': List=[u] self. Dfsvisit (G, U, list)Print "'. Join ([I.key forIinchList]) defdfsvisit (self, G, U, list):Global Time Time= time + 1U.D=Time U.color='Gray' forVinchU.adj:ifV.color = =' White': List.append (v) V.pi=u self. Dfsvisit (G, V, list) U.color='Black' Time= time + 1U.F= Timedefgraphtransposition (Self, G): forUinchG.v:u.adj=(u.adj,[]) forUinchG.V: forVinchu.adj[0]: v.adj[1].append (U) forUinchG.v:u.adj= U.adj[1] returnGdefstronglyconnectedcomponents (Self, G): self. Dfs (G) g_transposition=Self . Graphtransposition (G) g_transposition.v.sort (Key=LambdaV:V.F, reverse=True) self. Dfs (g_transposition)if __name__=='__main__': A,b,c,d,e,f,g,h= [Vertex (i) forIinch['a','b','C','D','e','F','g','h']] A.adj=[b] B.adj=[c,e,f] C.adj=[D,g] D.adj=[C,h] E.adj=[a,f] F.adj=[g] G.adj=[F,h] H.adj=[h] G=Graph () g.v=[A,b,c,d,e,f,g,h] m=solution () m.stronglyconnectedcomponents (G)
[Introduction to algorithms] strong connectivity Component @ Python