Finding cycle of 3 nodes ( or triangles) in a graph

后端 未结 11 2163
南旧
南旧 2020-12-31 15:42

I am working with complex networks. I want to find group of nodes which forms a cycle of 3 nodes (or triangles) in a given graph. As my graph contains about million edges, u

11条回答
  •  遥遥无期
    2020-12-31 16:33

    Assuming its an undirected graph, the answer lies in networkx library of python. if you just need to count triangles, use:

    import networkx as nx
    tri=nx.triangles(g)
    

    But if you need to know the edge list with triangle (triadic) relationship, use

    all_cliques= nx.enumerate_all_cliques(g)
    

    This will give you all cliques (k=1,2,3...max degree - 1)

    So, to filter just triangles i.e k=3,

    triad_cliques=[x for x in all_cliques if len(x)==3 ]
    

    The triad_cliques will give a edge list with only triangles.

提交回复
热议问题