[演算法導論]強連通分量 @ Python

來源:互聯網
上載者:User

標籤:

class Graph:    def __init__(self):        self.V = []class Vertex:    def __init__(self, x):        self.key = x        self.color = ‘white‘        self.d = 10000        self.f = 10000        self.pi = None        self.adj = []class Solution:    def Dfs(self, G):        for u in G.V:            u.color = ‘white‘            u.pi = None        global time        time = 0        for u in G.V:            if u.color == ‘white‘:                list=[u]                self.DfsVisit(G, u, list)                print ‘‘.join([i.key for i in list])    def DfsVisit(self, G, u, list):        global time        time = time + 1        u.d = time        u.color = ‘gray‘        for v in u.adj:            if v.color == ‘white‘:                list.append(v)                v.pi = u                self.DfsVisit(G, v, list)        u.color = ‘black‘        time = time + 1        u.f = time    def GraphTransposition(self, G):        for u in G.V:            u.adj = (u.adj,[])        for u in G.V:            for v in u.adj[0]:                v.adj[1].append(u)        for u in G.V:            u.adj = u.adj[1]        return G    def StronglyConnectedComponents(self, G):        self.Dfs(G)        G_Transposition = self.GraphTransposition(G)        G_Transposition.V.sort(key=lambda v: v.f, reverse=True)        self.Dfs(G_Transposition)if __name__ == ‘__main__‘:    a,b,c,d,e,f,g,h = [Vertex(i) for i in [‘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)

 

[演算法導論]強連通分量 @ Python

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.