在python中寻找最大团

2024-05-18 10:53:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我最近一直在尝试将maximum-clique算法移植到python,但是我似乎无法正确实现它。目标是找到图中最大的集团。我的目标是实现,如this文章中所述,图1(简单变体)。我当前的代码如下:

import networkx as nx
import operator

if __name__ == "__main__":


    ## read the graph
    G = nx.Graph()
    G.add_edge(1,2)
    G.add_edge(1,3)
    G.add_edge(3,2)
    G.add_edge(3,4)


    C = nx.coloring.greedy_color(G, strategy=nx.coloring.strategy_largest_first)
    R = G.nodes()

    qu = []
    qmax = []    

    def maxClique(R,C,qu,qmax):

        while len(R) > 0:
            cdict= sorted(C.items(), key=operator.itemgetter(1),reverse=True)
            pivot = cdict[0][0]
            color = cdict[0][1]
            R.remove(pivot)

            if len(set(qu)) + int(color) > len(set(qmax)):
                qu.append(pivot)
                neighbours = G.neighbors(pivot)                
                intersection = [x for x in R if x in neighbours]

                if len(intersection) > 0:
                    subgraph = G.subgraph(intersection)
                    Cx = nx.coloring.greedy_color(subgraph, strategy=nx.coloring.strategy_largest_first)
                    maxClique(intersection,Cx,list(set(qu)),qmax)

                elif len(qu) > len(qmax):
                    qmax = qu
                    qu = qu.remove(pivot)

                else:
                    return qmax

    print(maxClique(R,C,qu,qmax))

因此,该算法必须将{1,2,3}标识为max团。在


Tags: addlenifcolorpivotnxsetedge